6.1 Intentionally Raising Exceptions
In Python, you can deliberately raise exceptions using the raise
statement. This lets you signal when an error or incorrect situation arises in your program. Let's check out various ways to use the raise
statement and how to repackage exceptions.
Raising Standard Exceptions
The general syntax for this operation looks like:
raise exception
You can raise standard exceptions like Exception
, TypeError
, and others by passing them the appropriate messages.
Example: raise Exception
def check_number(value):
if value < 0:
raise Exception("Sorry, no numbers below zero")
try:
check_number(-5)
except Exception as e:
print(f"Exception caught: {e}")
In this example, if the value is less than zero, an Exception
is raised with the message "Sorry, no numbers below zero"
.
Example: raise TypeError
def check_integer(value):
if not isinstance(value, int):
raise TypeError("Only integers are allowed")
try:
check_integer("string")
except TypeError as e:
print(f"Exception caught: {e}")
In this example, if the value isn't an integer, a TypeError
is raised with the message "Only integers are allowed"
.
6.2 Repackaging Exceptions
Sometimes you need to catch one exception and raise another one, providing more specific or useful information. You can do this with the raise
... from
statement, which keeps the original exception as the cause for the new one.
The general syntax for this operation looks like:
raise new_exception from old_exception
Example: Repackaging an Exception
class EmptyVariableError(Exception):
pass
def check_non_empty(value):
if value == "":
raise ValueError("The variable is empty")
try:
check_non_empty("")
except ValueError as e:
raise EmptyVariableError("Empty variable detected") from e
In this example, if the variable's value is empty, a ValueError
is first raised with the message "The variable is empty"
. This exception is then caught, and a new exception EmptyVariableError
is raised with the message "Empty variable detected"
, with the original exception passed using from
.
6.3 Analyzing Repackaged Exceptions
Using the raise
... from
statement allows you to preserve information about the exception chain, which can be super handy for debugging. You can analyze repackaged exceptions and their causes.
Example of Analyzing Repackaged Exceptions:
class EmptyVariableError(Exception):
pass
def check_non_empty(value):
if value == "":
raise ValueError("The variable is empty")
try:
check_non_empty("")
except ValueError as e:
raise EmptyVariableError("Empty variable detected") from e
Running the code above will result in the following output:
Traceback (most recent call last): File "example.py", line 8, in
check_non_empty("") File "example.py", line 5, in check_non_empty raise ValueError("The variable is empty") ValueError: The variable is empty
The above exception was the direct cause of the following exception:
Traceback (most recent call last): File "example.py", line 10, in
raise EmptyVariableError("Empty variable detected") from e EmptyVariableError: Empty variable detected
The first error (highlighted in green)
is the original error that happened somewhere deep in the code. Sometimes such errors pop up every now and then, and that's normal behavior for a program.
The second error (highlighted in blue)
is a more high-level error. Your program or framework should know how to handle it. But if you wanna dig deeper and figure out why the error happened, the green error is your friend for that.
All of this is done very cleverly.
GO TO FULL VERSION