Selected topic
Error Handling
Prefer practical output? Use related tools below while reading.
python
try:
# code to be executed
except ExceptionType:
# code to handle the exception
Here's an example that uses the ZeroDivisionError exception type:
python
def divide_numbers(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
print("Cannot divide by zero!")
return Noneprint(divide_numbers(10, 2)) # Output: 5.0
print(divide_numbers(10, 0)) # Output: Cannot divide by zero!
divide_numbers function attempts to perform a division operation inside the try block. If the denominator is zero (i.e., a ZeroDivisionError occurs), the except block catches the exception and prints an error message before returning None.python
try:
# code to be executed
except (TypeError, ZeroDivisionError):
# code to handle the exceptionsTypeError and ZeroDivisionError:python
def divide_numbers(a, b):
try:
result = a / b
return result
except (TypeError, ZeroDivisionError):
print("Invalid input or division by zero!")
return Noneprint(divide_numbers(10, 2)) # Output: 5.0
print(divide_numbers(10, 'a')) # Output: Invalid input or division by zero!
print(divide_numbers(10, 0)) # Output: Invalid input or division by zero!
TypeError or a ZeroDivisionError occurs during the execution of the try block, the except block catches the exception and prints an error message before returning None.python
try:
# code to be executed
finally:
# code to be executed alwayspython
def divide_numbers(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
print("Cannot divide by zero!")
return None
finally:
print("Cleanup code executed!")print(divide_numbers(10, 2)) # Output: Cleanup code executed!
5.0
print(divide_numbers(10, 0)) # Output: Cannot divide by zero! Cleanup code executed!
ZeroDivisionError occurs during the execution of the try-except block.I hope these examples help illustrate the basics of error handling in Python!