Exception handling is a mechanism in Python to handle runtime errors, ensuring that your program can deal with unexpected events gracefully.
The try and except blocks are used to handle exceptions.
Syntax:
try:
# Code that may raise an exception
except SomeException as e:
# Code that runs if the exception occurs
print(f"An error occurred: {e}")
Example:
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
You can handle multiple exceptions by specifying them in a tuple.
Example:
try:
result = 10 / 0
except (ZeroDivisionError, TypeError) as e:
print(f"Error: {e}")
The else block runs if no exceptions are raised in the try block.
Example:
try:
result = 10 / 2
except ZeroDivisionError as e:
print(f"Error: {e}")
else:
print(f"Result: {result}")
The finally block always runs, regardless of whether an exception occurred. It is typically used for cleanup actions.
Example:
try:
file = open('example.txt', 'r')
content = file.read()
except FileNotFoundError as e:
print(f"Error: {e}")
finally:
file.close()
print("File closed.")
You can raise exceptions using the raise keyword.
Example:
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
try:
result = divide(10, 0)
except ValueError as e:
print(f"Error: {e}")
You can define your own exceptions by creating a class that inherits from the built-in Exception class.
Example:
class CustomError(Exception):
pass
def check_value(value):
if value < 0:
raise CustomError("Value cannot be negative")
try:
check_value(-1)
except CustomError as e:
print(f"Error: {e}")