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.