Error handling
Essential to prevent application crashes.
Example without error handling
python
print(10 / 0)
# ZeroDivisionError: division by zero
# code execution stops hereUse try/except block
Start with try:, end with except. you can use multiple except blocks. you can also use else and finally blocks.
python
try:
# code block
pass
except TypeError as e:
# this block is executed if TypeError occurs
pass
except ZeroDivisionError as e:
# this block is executed if ZeroDivisionError occurs
pass
except Exception as e:
# this block is executed if any other error occurs
# when you do not know the type of error, use this
pass
else:
# optional
# this block is executed if no error occurs
pass
finally:
# optional
# this block is always executed no matter what
pass
# code execution continues hereExample using try/except block
Here we used multiple errortype in one except block.
python
try:
print(10 / 0)
except (ZeroDivisionError, Exception) as e:
print(e)
# division by zeroDo not use plain except block
Not recommended. Because you cannot catch the error type.
python
try:
print(10 / 0)
except:
print('Some error occured')At least use except Exception as e to catch the error.
Use raise to generate an error
python
def divide(a, b):
if b == 0:
# raise an error so that you can catch it later
raise ValueError('Cannot divide by zero')
return a / b
try:
divide(10, 0)
except ValueError as e:
print(e)
# Cannot divide by zeroException class
All error types are subclasses of the Exception class.