You use the “raise” keyword to throw a Python exception manually. You can add a message to describe the exception type or reason.
Be specific in your message, e.g.:
raise ValueError('A very specific bad thing happened.')
Note: Avoid raising a generic Exception
. To catch it, you’ll have to catch all other more specific exceptions that subclass it.
Python throw exception
A simple example is a code checking a condition and raising the exception, if the condition is True raise the exception to warn the user or the calling application.
def demo_bad_catch():
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('Caught this error: ' + repr(error))
demo_bad_catch()
Output:
And more specific catches won’t catch the general exception:
def demo_no_catch():
try:
raise Exception('general exceptions not caught by specific handling')
except ValueError as e:
print('we will not catch exception: Exception')
demo_no_catch()
Source: https://stackoverflow.com/questions/2052390/
How to raise an exception in a try-except-else statement?
Answer: try Python assert keyword with an error message.
import logging
for i in range(5):
try:
assert(1 == i)
print("try", i)
except Exception:
logging.exception("error")
else:
assert(1 == 1)
print("else", i)
finally:
print("finally", i, "\n")
print("end")
In Python 3 there are four different syntaxes for raising exceptions:
- raise exception
- raise exception (args)
- raise
- raise exception (args) from original_exception
Do comment if you have any doubts or suggestions on this Python exception-handling topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.