Exceptions
Exceptions in Python are events that occur during the execution of a program that disrupt the normal flow of instructions. Python uses exception handling to manage these errors and exceptional situations.
The basic structure for exception handling in Python uses the try and except statements.
try:
ㅤㅤ# Code that might raise an exception
ㅤㅤresult = 10 / 0
except ZeroDivisionError:
ㅤㅤprint("Cannot divide by zero!")
You can handle different types of exceptions using multiple except blocks.
try:
ㅤㅤx = int(input("Enter a number: "))
ㅤㅤresult = 10 / x
except ValueError:
ㅤㅤprint("Invalid input. Please enter a number.")
except ZeroDivisionError:
ㅤㅤprint("Cannot divide by zero!")
You can raise exceptions using the raise statement.
def validate_age(age):
ㅤㅤif age < 0:
ㅤㅤㅤㅤraise ValueError("Age cannot be negative")
ㅤㅤreturn age
try:
ㅤㅤage = validate_age(-5)
except ValueError as e:
ㅤㅤprint(f"Error: {e}")
You can create custom exceptions by inheriting from the built-in Exception class.
class CustomError(Exception):
ㅤㅤpass
try:
ㅤㅤraise CustomError("This is a custom error")
except CustomError as e:
ㅤㅤprint(f"Caught an exception: {e}")
Python allows you to chain exceptions using the from keyword.
try:
ㅤㅤraise ValueError("This is the original error")
except ValueError as e:
ㅤㅤraise RuntimeError("A new error occurred") from e