Python error handling
Created By: chatGPT
In Python, error handling is crucial for creating robust applications. You can manage exceptions using the
try
, except
, else
, and finally
blocks. This lets you capture and respond to errors gracefully without crashing the program.try:
# Code that may raise an exception
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print('You cannot divide by zero!')
else:
print('Division successful. Result:', result)
finally:
print('Execution completed.')
The
try
block contains the code that might throw an exception. If an exception occurs, the control will jump to the except
block where you can handle the error. The else
block runs if the code in try
runs without any exceptions. The finally
block will always execute, regardless of whether an exception was raised or not, making it ideal for cleanup actions.try:
# Open a file and read its content
with open('sample.txt', 'r') as file:
data = file.read()
except FileNotFoundError:
print('File not found!')
else:
print('File content:', data)
finally:
print('Finished attempting to read the file.')
You can also catch multiple exceptions together or use an
as
clause to access the exception object. This allows you to inspect the error for more in-depth debugging.try:
# Code that may raise different exceptions
value = int('string') # Raises ValueError
result = 10 / 0 # Raises ZeroDivisionError
except (ValueError, ZeroDivisionError) as e:
print('An error occurred:', e)
else:
print('Operation successful:', result)
finally:
print('Error handling complete.')
Using custom exceptions can improve the error handling process. This involves creating your own exception classes by extending the built-in
Exception
class, which allows you to raise specific errors in your application.class CustomError(Exception):
pass
try:
raise CustomError('This is a custom error message')
except CustomError as e:
print('Caught a custom error:', e)
To summarize, effective error handling in Python is essential to avoid unexpected application crashes. By using
try
, except
, else
, and finally
, along with custom exceptions when needed, you can ensure that your applications can handle errors gracefully and remain user-friendly.try:
risky_operation()
except Exception as e:
logger.error('An error occurred:', exc_info=True)
print('Error handled.') # Graceful handling