Exception handling is a critical component of robust Python programming. It allows you to gracefully manage errors that might arise during program execution, preventing crashes and providing users with informative feedback. This tutorial delves into the fundamental concepts of exception handling in Python.
Table of Contents
1. try…except
The try...except
block is the foundation of exception handling. Code that might raise an exception is placed within the try
block. If an exception occurs, the corresponding except
block is executed.
try:
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Error: Division by zero!")
except TypeError:
print("Error: Type mismatch")
except Exception as e: # Catches any other exception
print(f"An unexpected error occurred: {e}")
else: # Optional else block, executes if no exception occurs
print(f"Result: {result}")
finally: # Optional finally block, always executes
print("This always executes.")
This example demonstrates handling a ZeroDivisionError
. Multiple except
blocks can handle different exception types. The optional else
block executes only if no exception occurs in the try
block. The finally
block, also optional, always executes, ideal for cleanup tasks like closing files.
2. raise Exception
The raise
statement lets you explicitly raise exceptions, signaling errors or exceptional conditions.
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
elif age > 120:
raise ValueError("Age is unrealistically high")
return age
try:
age = validate_age(-5)
print(f"Valid age: {age}")
except ValueError as e:
print(f"Error: {e}")
Here, validate_age
raises a ValueError
if the age is invalid. You can raise any built-in exception or create custom ones (classes inheriting from Exception
).
3. try…finally
The finally
block ensures that code within it always executes, regardless of exceptions. It’s essential for cleanup.
file = None
try:
file = open("my_file.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("File not found!")
finally:
if file:
file.close()
print("File closed.")
This guarantees the file is closed even if a FileNotFoundError
occurs, preventing resource leaks.
4. Common Built-in Exceptions
Python offers numerous built-in exceptions:
ZeroDivisionError
: Division by zero.TypeError
: Inappropriate type for an operation.ValueError
: Correct type, inappropriate value.FileNotFoundError
: File not found.IndexError
: Index out of range.KeyError
: Key not found in a dictionary.ImportError
: Import failure.NameError
: Name not found.
5. Creating Custom Exceptions
For more specific error handling, create custom exceptions by subclassing the Exception
class:
class InvalidInputError(Exception):
pass
def process_data(data):
if not data:
raise InvalidInputError("Data cannot be empty")
# ...rest of the data processing...
try:
process_data("")
except InvalidInputError as e:
print(f"Custom Error: {e}")
This allows for more granular error handling and improved code readability.
Effective exception handling is vital for writing robust and reliable Python programs. By anticipating and gracefully handling potential errors, you build more resilient and user-friendly applications.