Python Documentation

Exceptions

Exceptions in Python

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.

Try and Except Statements

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!")

Multiple Except Blocks

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!")

Raising Exceptions

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}")

Custom Exceptions

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}")

Exception Chaining

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