We have explored basic python till now from Set 1 to 4 (Set 1 | Set 2 | Set 3 | Set 4).
If you are a beginner, then you might be getting a lot of Tracebacks till now. The tracebacks are generated due to runtime errors.
Like other languages, python also provides the runtime errors via exception handling method with the help of try-except. Some of the standard exceptions which are most frequent include IndexError, ImportError, IOError, ZeroDivisionError, TypeError.
Exception is the base class for all the exceptions in python. You can check the exception hierarchy here.
Let us try to access the array element whose index is out of bound and handle the corresponding exception.
Second element = 2 An error occurred
A try statement can have more than one except clause, to specify handlers for different exceptions. Please note that at most one handler will be executed.
Error Occurred and Handled
If you change the value of ‘a’ to greater than or equal to 4, the the output will be
Value of b = Error Occurred and Handled
The output above is so because as soon as python tries to access the value of b, NameError occurs.
In python, you can also use else clause on try-except block which must be present after all the except clauses. The code enters the else block only if the try clause does not raise an exception.
The output for above program will be :
-5.0 a/b result in 0
The raise statement allows the programmer to force a specific exception to occur. The sole argument in raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from Exception).
The output of the above code will simply line printed as “An exception” but a Runtime error will also occur in the last due to raise statement in the last line. So, the output on your command line 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 contributed by Nikhil Kumar Singh(nickzuck_007)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Built-in Exceptions in Python
- First Class functions in Python
- Keywords in Python | Set 2
- Timeit in Python with Examples
- How to check if a string is a valid keyword in Python?
- User-defined Exceptions in Python with Examples
- Loops and Control Statements (continue, break and pass) in Python
- Python Modules
- Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix
- Important differences between Python 2.x and Python 3.x with examples
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Set 3 (Strings, Lists, Tuples, Iterations)
- Python | Set 2 (Variables, Expressions, Conditions and Functions)
- Python Language Introduction
- Python – The new generation Language