Introduction
Exception handling in Python is a crucial mechanism that ensures the smooth functioning of programs by managing errors and exceptions that may occur during execution. Python provides the try
, except
, else
, and finally
blocks to handle exceptions and execute specific code based on whether an exception occurs.
Key Concepts
try
Block: The code that may raise an exception is placed inside thetry
block.except
Block: The code that runs if an exception occurs in thetry
block.else
Block: The code that runs if no exception occurs in thetry
block.finally
Block: The code that always runs, regardless of whether an exception occurs or not.
Basic Syntax
try:
# Code that may raise an exception
risky_code()
except SomeException:
# Code that runs if the specified exception occurs
handle_exception()
else:
# Code that runs if no exception occurs
run_if_no_exception()
finally:
# Code that always runs
cleanup_code()
Examples
Basic Exception Handling with try
and except
try:
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
Output
You can't divide by zero!
Multiple except
Blocks
try:
value = int("abc")
except ValueError:
print("Invalid literal for int() with base 10.")
except TypeError:
print("Type error occurred.")
Output
Invalid literal for int() with base 10.
Using else
Block
The else
block runs if no exception occurs in the try
block.
try:
result = 10 / 2
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print("Division successful!")
Output
Division successful!
Using finally
Block
The finally
block runs regardless of whether an exception occurs or not.
try:
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
finally:
print("Execution completed.")
Output
You can't divide by zero!
Execution completed.
Combining try
, except
, else
, and finally
You can combine all four blocks to handle exceptions comprehensively.
try:
result = 10 / 2
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print("Division successful!")
finally:
print("Execution completed.")
Output
Division successful!
Execution completed.
Raising Exceptions
You can raise exceptions explicitly using the raise
keyword.
def divide(a, b):
if b == 0:
raise ValueError("The divisor cannot be zero.")
return a / b
try:
result = divide(10, 0)
except ValueError as e:
print(e)
finally:
print("Execution completed.")
Output
The divisor cannot be zero.
Execution completed.
Real-World Example: File Handling
Handling file operations often involves exceptions, such as when trying to open a file that doesn’t exist.
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found.")
else:
print("File content read successfully.")
print(content)
finally:
if 'file' in locals():
file.close()
print("File handling completed.")
Output (if the file exists)
File content read successfully.
... (file content) ...
File handling completed.
Output (if the file does not exist)
File not found.
File handling completed.
Conclusion
The try
, except
, else
, and finally
blocks in Python provide a robust framework for handling exceptions and ensuring the smooth execution of programs. By understanding and utilizing these blocks, you can write more resilient and error-resistant code, effectively managing potential errors and ensuring proper resource management.