Handling Exceptions with try
and except
In Python, you can handle exceptions using a try
...except
block. This structure allows you to gracefully manage exceptions and continue program execution without crashing. In this section, we'll explore how to use try
and except
to handle exceptions effectively.
1. The try
...except
Block
The try
...except
block is used to catch and handle exceptions. It has the following structure:
try:
# Code that may raise an exception
except ExceptionType:
# Code to handle the exception
Here's how it works:
- The code inside the
try
block is executed. - If an exception of the specified
ExceptionType
occurs, the program jumps to the correspondingexcept
block. - The code inside the
except
block is executed to handle the exception.
2. Handling a Specific Exception
You can specify the type of exception to catch in the except
block. For example, to catch a ValueError
:
try:
number = int("abc")
except ValueError:
print("A ValueError occurred. Please enter a valid number.")
3. Handling Multiple Exceptions
You can catch multiple exception types by using multiple except
blocks:
try:
# Code that may raise an exception
except ExceptionType1:
# Handle ExceptionType1
except ExceptionType2:
# Handle ExceptionType2
This allows you to tailor your error-handling code to different exception scenarios.
4. The else
Block
You can include an else
block that is executed if no exceptions occur in the try
block. This is useful for executing code when everything goes smoothly:
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("The result is:", result)
5. The finally
Block
The finally
block is always executed, whether an exception is raised or not. It is often used for cleanup operations, such as closing files or releasing resources:
try:
# Code that may raise an exception
except ExceptionType:
# Handle the exception
finally:
# Code that always runs, e.g., cleanup code
6. Raising Exceptions
You can raise exceptions explicitly using the raise
statement to signal specific error conditions in your code:
def divide(a, b):
if b == 0:
raise ZeroDivisionError("Cannot divide by zero")
return a / b
7. Exception Objects
When an exception is raised, Python creates an exception object containing information about the exception. You can access this information using the as
keyword in the except
block:
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Exception: {e}")
Handling exceptions with try
and except
is crucial for writing robust and reliable code. Proper error handling allows your program to gracefully respond to errors and prevent crashes.