throwing an exception python
raise Exception("message")
buildin exceptions in python
BaseException
├── SystemExit # Raised by the sys.exit() function.
├── KeyboardInterrupt # Raised when the user hits the interrupt key (ctrl-c).
└── Exception # User-defined exceptions should be derived from this class.
├── ArithmeticError # Base class for arithmetic errors.
│ └── ZeroDivisionError # Raised when dividing by zero.
├── AttributeError # Raised when an attribute is missing.
├── EOFError # Raised by input() when it hits end-of-file condition.
├── LookupError # Raised when a look-up on a collection fails.
│ ├── IndexError # Raised when a sequence index is out of range.
│ └── KeyError # Raised when a dictionary key or set element is not found.
├── NameError # Raised when a variable name is not found.
├── OSError # Errors such as “file not found” or “disk full” (see Open).
│ └── FileNotFoundError # When a file or directory is requested but doesn't exist.
├── RuntimeError # Raised by errors that don't fall in other categories.
│ └── RecursionError # Raised when the maximum recursion depth is exceeded.
├── StopIteration # Raised by next() when run on an empty iterator.
├── TypeError # Raised when an argument is of wrong type.
└── ValueError # When an argument is of right type but inappropriate value.
└── UnicodeError # Raised when encoding/decoding strings to/from bytes fails.
error handling Pyhtin
# taking input from the user
try:
age = int(input("Please enter your age: "))
print(age)
except:
print("please enter a number instead! ")
print('bye')
# if you wanna ask their age until they enter the correct number use While Loop
while True:
try:
age = int(input("Please enter your age: "))
print(age)
except:
print("please enter a number instead! ")
else:
break
python except exception as e
try:
# Code to test / execute
print('Test')
except (SyntaxError, IndexError) as E: # specific exceptions
# Code in case of SyntaxError for example
print('Synthax or index error !')
except :
# Code for any other exception
print('Other error !')
else:
# Code if no exception caught
print('No error')
finally:
# Code executed after try block (success) or any exception (ie everytime)
print('Done')
# This code is out of try / catch bloc
print('Anything else')
how to use except statement in python
>>> def divide(x, y):
... try:
... result = x / y
... except ZeroDivisionError:
... print("division by zero!")
... else:
... print("result is", result)
... finally:
... print("executing finally clause")
...
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'
catch error data with except python
import sys
try:
S = 1/0 #Create Error
except: # catch *all* exceptions
e = sys.exc_info()
print(e) # (Exception Type, Exception Value, TraceBack)
############
# OR #
############
try:
S = 1/0
except ZeroDivisionError as e:
print(e) # ZeroDivisionError('division by zero')
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us