Introduction
In addition to handling exceptions raised by Python itself, you can also raise exceptions in your own code using the Python raise
statement. This allows you to indicate that an error has occurred under certain conditions, even if it’s not due to a runtime error generated by the Python system.
Raising Exceptions in Your Code
To raise an exception, you simply use the raise
keyword followed by the type of exception you want to raise. You can also optionally provide an error message that describes the reason for raising the exception.
Here’s the basic syntax for raising exceptions:
raise ExceptionType("Error message")
You can also raise an exception without a message with the following syntax:
raise ExceptionType
Suppose you’re writing a function to calculate the factorial of a number, and you want to restrict it to non-negative integers only, since the factorial is not defined for negative numbers. You can raise a ValueError
if a negative number is provided as input.
A factorial is the product of all positive integers less than or equal to a given number, denoted by an exclamation mark (n!). For example, 6 factorial (6!) is \times 2 \times 3 \times 4 \times 5 \times 6 = 720.
Example:
def factorial(n): if n < 0: raise ValueError("Factorial is not defined for negative numbers.") result = 1 for i in range(1, n + 1): result *= i return result try: print(factorial(5)) # Valid function argument print(factorial(-1)) # Raises ValueError except ValueError as e: print(e)
Output:
120 Factorial is not defined for negative numbers.
In the example above, the factorial
function raises a ValueError
(line 3) with a custom error message if the input, n
, is negative. Inside the try block (lines 9 and 10), we call the factorial()
function with both a valid input (5
) and an invalid input (-1
). When the function raises a ValueError
for the invalid input, we catch it in the except
block (line 13) and print the error message.
Summary & Reference for Raising Exceptions With the Python raise Statement
You can raise exceptions in your own code using the Python raise
statement. This allows you to indicate that an error has occurred under certain conditions when it’s not due to a runtime error generated by Python.
To raise an exception, use the raise
keyword followed by the type of exception and an optional error message, if needed.
raise ExceptionType("Error message")
or
raise ExceptionType