How can I handle exceptions in Python?
Use `try` and `except` blocks to catch and handle exceptions. This prevents crashes and allows for graceful error recovery in your code.
Exception handling in Python is a critical feature that allows you to manage errors gracefully without crashing your program. By using try
and except
blocks, you can catch exceptions that may occur during runtime and provide an alternative response. The basic syntax is as follows:
try:
# Code that may raise an exception
except ExceptionType:
# Code that executes if an exception occurs
For example:
try:
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print('Cannot divide by zero!')
You can also catch multiple exceptions:
try:
# Some code
except (TypeError, ValueError) as e:
print(f'Caught an exception: {e}')
If you want to execute cleanup code regardless of whether an exception occurred, you can use the finally
block:
try:
# Code that may raise an exception
finally:
# Code that executes no matter what
By effectively handling exceptions, you can create robust applications that provide meaningful feedback to users and handle errors gracefully.