If you want to set up manually python exception then you can do in Python. Python raise exception is the settlement to throw a manual error.
It’s always suggestible Don’t raise generic exceptions. Learn about Generic exception must read this tutorial – Python exception Handling | Error Handling
In Python 3 there are 4 different syntaxes of raising exceptions.
raise exception– No argument print system default message
raise exception (args)– with an argument to be printed
raise– without any arguments re-raises the last exception
raise exception (args) from original_exception– contain the details of the original exception
<span class="k">raise</span> <span class="ne">ValueError('I am erorr')</span>
In this tutorial, we used
raise exception(args) to raise an exception. The
args will be print by exception object.
Python raise exception Example:
It’s a simple example for raise exception with a custom message. The sole argument to
raise shows the exception to be raised.
print('An raise exception !')
Let’s see Another Example
If you want an throwing error on any condition, like if negative values have entered. So you can do it like that example.
a = int(input("Enter a positive Number: "))
if a <= 0:
raise ValueError("it's not a positive number!")
except ValueError as ve:
QA: How to raise an exception in Python 3
it can be your interview question. There is simply you have to write an
raise exception(args) in try except block, same as upper examples.
Must read this thread on StackOverflow: https://stackoverflow.com/questions/2052390/manually-raising-throwing-an-exception-in-python
Bonus: this tutorial is not cover the exception and error handling, for that you must follow this tutorial.
Do comment if you have any doubt and suggestion on this tutorial.
Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
All examples are of raise exception in python 3, so it may change its different from python 2 or upgraded versions.