W3docs

Manually raising (throwing) an exception in Python

In Python, you can raise an exception using the raise statement.

In Python, you can raise an exception using the raise statement. Here is an example:

Raising an exception in Python

try:
    raise Exception("This is an exception")
except Exception as e:
    print(e)

You can also specify the type of exception to raise. For example:

Raising a specific exception in Python (ValueError)

try:
    raise ValueError("Invalid value")
except Exception as e:
    print(e)

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

You can also raise an exception with a custom message and include the original traceback information using the from keyword:

Raising an exception with a chained traceback in Python

try:
    # some code here
except Exception as e:
    raise ValueError("Custom error message") from e

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.