Python raise keyword. In python we can raise exception by using raise keyword. We have already gone through detailed overview on in-built Python exceptions and how it is being handled with python try except & finally statements.
Python gives your flexibility to raise exception whenever you want in the program. It is very powerful keyword and having unique features in it.
Mostly people are using python raise – keyword in conditional block to decide when and where to raise an exception.
When you specify raise keyword in your code and the moment program execution reaches that point – immediately exception is being raised by skipping further statements.
An interpreter doesn’t see, whether do you really have an error in your code or not. It simply raises an exception as per specified exception name.
Python raise keyword most often used in try block for various reasons for instance, to cross verify whether exceptions are properly getting raised and check its execution flow, to avoid the program execution termination, etc.
Use raise keyword in try except
It is very effective way to check whether your exceptional handling code – try/except block working properly without involving end user.
Observe this example – We are performing division of two numbers by taking inputs from users.
In this case we know ValueError exception can occur if user enter non-digit number. We have already seen this example here.
Now we could test this exception by raising ValueError exception manually in the code, irrespective of user inputs.
Note this result – we have entered correct input values still ValueError exception encountered due to raise keyword specified in try block code.