Raise Custom Exceptions
Sometimes you need to signal an error condition that isn't a built-in Python exception. You can do this with the raise statement, which allows you to create and trigger your own exceptions. This is useful for making your application's error handling more specific and descriptive.
First, let's see how to raise a built-in exception. In the WebIDE, open the file ~/project/raise_exception.py and add the following code:
def check_positive(number):
if number <= 0:
raise ValueError("Input must be a positive number")
print(f"The number {number} is positive.")
try:
check_positive(-5)
except ValueError as e:
print(f"Caught an exception: {e}")
try:
check_positive(10)
except ValueError as e:
print(f"Caught an exception: {e}")
Save the file and run it from the terminal:
python ~/project/raise_exception.py
The output will be:
Caught an exception: Input must be a positive number
The number 10 is positive.
Here, the check_positive function raises a ValueError if the input is not positive, which is then caught by the except block.
Now, let's define and raise a custom exception. Custom exceptions are classes that inherit from the built-in Exception class.
In the WebIDE, open the file ~/project/custom_exception.py and add the following code:
class NegativeNumberError(Exception):
"""Custom exception raised for negative numbers."""
pass
def process_positive_number(number):
if number < 0:
raise NegativeNumberError("Negative numbers are not allowed")
print(f"Processing positive number: {number}")
try:
process_positive_number(-10)
except NegativeNumberError as e:
print(f"Caught custom exception: {e}")
try:
process_positive_number(20)
except NegativeNumberError as e:
print(f"Caught custom exception: {e}")
Save the file and run it from the terminal:
python ~/project/custom_exception.py
The output will be:
Caught custom exception: Negative numbers are not allowed
Processing positive number: 20
In this example, we defined our own NegativeNumberError and raised it under a specific condition. The try...except block then specifically catches this custom error type, making the error handling more precise.