4.1 Catching Multiple Exceptions
Python lets you handle multiple exceptions using several except blocks or a single except block with a tuple of exceptions. Let's look at both approaches.
Multiple except Blocks
You can use multiple except blocks to handle different types of exceptions differently.
try:
# Code that may raise an exception
result = int("abc")
except ValueError:
print("Error: invalid value.")
except ZeroDivisionError:
print("Error: division by zero.")
Single except Block with a Tuple of Exceptions
You can handle multiple exceptions in a single except block by passing them as a tuple.
try:
# Code that may raise an exception
result = int("abc")
except (ValueError, ZeroDivisionError) as e:
print(f"An error occurred: {e}")
Using except NameError as var
When handling exceptions, you can use the syntax except <ExceptionType> as <variable> to access the exception object. This lets you access information about the exception like the error message and other attributes.
try:
# Code that may raise NameError
print(undeclared_variable)
except NameError as e:
print(f"An error occurred: {e}")
print(f"Error type: {type(e)}")
4.2 Error Variable Scope
The variable that stores the exception (e in the above example) is available only within its except block. Outside of this block, the variable is not accessible.
try:
# Code that may raise NameError
print(undeclared_variable)
except NameError as e:
print(f"An error occurred: {e}")
print(f"Error type: {type(e)}")
# Here, e is no longer available, and the next line will cause a NameError
# print(e) # NameError: name 'e' is not defined
If you want to do something important with the exception outside of its block, you need to save it in a separate variable. Example:
exception = None
try:
# Code that may raise an exception
result = int("abc")
except ValueError as e:
exception = e
print("Error: invalid value.")
except ZeroDivisionError as e:
exception = e
print("Error: division by zero.")
print(exception)
Notice that the exception variable keeps the last occurred exception, which can be useful for processing outside the try block.
4.3 What's Useful in an Error
An exception object contains information about the error. Depending on the type of exception, the object can contain different attributes.
Here are some common attributes available for most exceptions:
-
args: A tuple containing the arguments passed when the exception was created. Usually, this is the error message. -
message: A string containing the error message (in some exceptions). -
__str__: A method returning the string representation of the exception. This method is used to get the text representation of the error, which will be returned when using theprint()function on an exception object.
Example:
try:
# Code that may raise ValueError
result = int("abc")
except ValueError as e:
print(f"An error occurred: {e}")
print(f"Error arguments: {e.args}")
print(f"Error message: {str(e)}")
Example of Handling Multiple Exceptions
try:
# Code that may raise several types of exceptions
result = 10 / 0
except (ValueError, ZeroDivisionError) as e:
print(f"An error occurred: {e}")
print(f"Error type: {type(e)}")
print(f"Error arguments: {e.args}")
If a ValueError or ZeroDivisionError occurs, it will be caught by the except block. Information about the exception will be available through the e variable. The output will include the error type and the arguments passed when the exception was created.
GO TO FULL VERSION