Introduction¶
Error handling is an essential part of programming in Python. It allows you to anticipate and manage errors that may occur during the execution of your code.
try:
x = 5 / 0
except ZeroDivisionError:
print("Error: Division by zero is not allowed!")
Error: Division by zero is not allowed!
Types of Errors¶
Built in¶
try:
x = 5 / 2
except ZeroDivisionError:
print("Error: Division by zero is not allowed!")
else:
print("No errors occurred!")
No errors occurred!
try:
x = 5 / 0
except ZeroDivisionError:
print("Error: Division by zero is not allowed!")
finally:
print("This code will always be executed!")
Error: Division by zero is not allowed!
This code will always be executed!
Custom exceptions¶
class CustomError(Exception):
pass
try:
raise CustomError("This is a custom error!")
except CustomError as e:
print(f"Error: {e}")
Error: This is a custom error!