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.
All these exceptions are default and python interpreter decide when to raise the exception but WHAT if you want to raise an exception?
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.
If there would be chances of an exception can occur in your code where you already applied, try/except blocks but you want to test it then you can add raise keyword there.
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.