Manually raising (throwing) an exception in Python
In Python, you can raise an exception using the raise
statement. Here is an example:
You can also specify the type of exception to raise. For example:
Watch a video course
Python - The Practical Guide
You can also raise an exception with a custom message and include the original traceback information using the from
keyword:
try:
# some code here
except SomeException:
raise ValueError("Custom error message") from original_exception
Keep in mind that when you raise an exception, the current function execution is interrupted and the control is passed to the nearest enclosing try-except
block that handles the exception. If no such block is found, the program will terminate and the exception will be propagated to the caller.
It is a good practice to raise exceptions when something unexpected or invalid occurs in your code, so that the caller can handle the error appropriately.