Error handling in Python is done with try
, except
, else
, and finally
statements. This structure allows you to gracefully handle errors and perform cleanup operations if needed.
Basic Error Handling
try:
# Code that might raise an exception
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
try: Block of code that might raise an exception.
except: Code to execute if an exception occurs. You can specify specific error types like ZeroDivisionError
or use a general exception handler.
Catching Multiple Exceptions
You can catch multiple specific exceptions by listing them in a tuple or by using multiple except
blocks.
try:
result = int("abc")
except (ValueError, TypeError) as e:
print(f"Error occurred: {e}")
Or:
try:
result = int("abc")
except ValueError:
print("Error: Cannot convert string to integer.")
except TypeError:
print("Error: Invalid type used.")
Using a General Exception
To catch any exception, use except Exception
or simply except
. This can be helpful for logging or debugging, but it’s usually good to handle specific errors where possible.
try:
result = 10 / 0
except Exception as e:
print(f"An unexpected error occurred: {e}")
else
Clause
The else
block runs if no exceptions were raised in the try
block.
try:
result = 10 / 2
except ZeroDivisionError:
print("Error: Division by zero.")
else:
print("No errors occurred. Result is:", result)
finally
Clause
The finally
block runs no matter what, whether an exception occurred or not. It’s often used for cleanup actions (e.g., closing files or database connections).
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("Error: File not found.")
finally:
if 'file' in locals():
file.close()
print("File closed.")
Raising Exceptions
You can use raise
to throw an exception if a condition isn’t met.
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero.")
return a / b
try:
print(divide(10, 0))
except ValueError as e:
print(e)
Custom Exception Classes
You can create custom exceptions by subclassing Python’s built-in Exception
class.
class CustomError(Exception):
pass
def risky_function():
raise CustomError("This is a custom error.")
try:
risky_function()
except CustomError as e:
print(e)