Categories
Python Answers

How to manually raise or throw an exception in Python?

Spread the love

Sometimes, we want to manually raise or throw an exception in Python.

In this article, we’ll look at how to manually raise or throw an exception in Python.

How to manually raise or throw an exception in Python?

To manually raise or throw an exception in Python, we can use the raise keyword.

For instance, we write:

try:
    raise ValueError('Represents a hidden bug, do not catch this')
    raise Exception('This is the exception you expect to handle')
except Exception as error:
    print(repr(error))

We use raise with ValueError to raise ValueError with a message.

Then we use the except clause to catch the Exception error, which is the parent class of all exceptions.

So the print call will print ValueError('Represents a hidden bug, do not catch this').

And the Exception exception is never raised.

Conclusion

To manually raise or throw an exception in Python, we can use the raise keyword.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *