Basically, an exception is an abnormal condition or error that occurs during the execution of a program. Whenever an exception occurs in a program, the execution of the program halts and the further instruction of the programs are not executed.
We need to handle these exceptions in order to ensure the normal execution of the program.
Some of the common exceptions that occur in Python programs while executing are:
- NameError: This error occurs when a name is not found.
- ZeroDivisionError: When a number is divided by zero, ZeroDivisionError occurs.
- IndentationError: This error occurs due to the wrong indentation.
- IOError: When Input-Output operation fails, IOError occurs.
So, in Python we use the try, catch, except and finally to handle the exceptions.
In the Python program, the line of code that may throw exceptions is placed in the try block.
The try block should have except block with it to handle the exception. As an illustration – If any exception occurs in try block then the statements in except block will be executed.
In this case, the else block will be executed if no exception occurs.
If we want a piece of executable code, which we cannot skip under any circumstances, then we need to put this code in the finally block.
Here, in this tutorial, we learned all the basics of Python which are variables, string, numbers, data types, tuples, lists, sets, dictionary, conditional statements, loops, user-defined functions, and exception handling..