Like other languages, python also provides runtime errors through the try-exc exception handling method. Some of the standard exceptions that are the most common include IndexError, ImportError, IOError, ZeroDivisionError, TypeError.
Exception is the base class for all exceptions in Python. You can check the exception hierarchy here .
Let’s try to access to the array element whose index is out of bounds and handle the corresponding exception.
Second element = 2 An error occurred
A try statement can have more than one condition, besides a clause, to specify handlers for various exceptions. Note that no more than one handler will be executed.
Error Occurred and Handled
If you change the value of ’a’ to greater than or equal to 4, the output will be
Value of b = Error Occurred and Handled
The output above is this because as soon as python tries to access the value of b, a NameError occurs.
In python, you can also use the else clause in the block try-exc, which must be present after all clauses except. Code enters the else block only if the try clause does not throw an exception.
| tr> |
The output for the above program will be:
-5.0 a / b result in 0
The lift operator allows the programmer to force a specific exception to be thrown. The only argument in a raise indicates an exception that should be raised. It must be either an exception instance or an exception class (a class derived from Exception).
The output of the above code will just be printed as an "Exception" string, but a runtime error will also occur in the latter because of the promotions operator on the last line. So your command line output will look like
Traceback (most recent call last): File "003dff3d748c75816b7f849be98b91b8.py", line 4, in raise NameError ("Hi there") # Raise Error NameError: Hi there
This article is courtesy of Nikhil Kumar Singh (nickzuck_007)
Please write comments if you find something wrong or if you would like to share additional information on the topic under discussion