Now that you know how to catch exceptions that might come up in your programs, it's time to learn how to purposefully make them happen when you want them to.
Raise a Python Exception
You can bring up an exception at any point in your code using the raise keyword:
raise Exception
Whenever your code raises an exception, the program will terminate unless you catch the exception you raised using a try except block.
When the raise statement is used, the program leaves its path of execution and searches for the nearest try except block where the exception might be caught. If the raise is not contained inside of a try except block, then the raised exception will terminate your program and display the exception.
Types of Exceptions
You can raise any of Python's built-in exceptions in this way, not just the Exception class:
age = int(input("Age: "))
if age < 0:
raise ValueError
In the example above, you explicitly raise a ValueError if the user input is below 0. This makes sense in the context of this specific code snippet.
The Python interpreter would raise a ValueError by itself if the user entered input that can't be converted to an integer. However, if they enter a negative number, Python would happily convert that to an integer.
But in the context of this script, this might not make any sense. Maybe you only want to collect user input if the person has already been born. Therefore, you can explicitly raise a ValueError in this conditional statement if the number the user entered is negative. But how would they know what went wrong?
Add an Exception Message
Additionally to raising an exception, you can add a message to the exception object by passing a string to its constructor:
age = int(input("Age: "))
if age < 0:
raise ValueError("Looks like you're not born yet.")
If a user enters a negative number, the script will exit and display the output you specified:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Looks like you're not born yet.
With this information added, the output becomes a little easier to understand for your users. Or, in this specific case, it might throw them into an existential crisis ¯\_(ツ)_/¯
You might already guess that passing this message is possible because of the object-oriented nature of Python exceptions. In the next lesson, you'll learn how to create your own custom exception objects that inherit from the Exception class.
Summary: Python Raise Exception
- Raising an exception can alert your program of an error
- The
raisekeyword is used to raise an exception - Custom error messages can be sent to the exception objects