Today I will take a new part of python for my tutorial series. In this part, you will learn Exception Handling.
I already told you the following:
Python language has various types of Exception Handling. I will tell you some exception handling in Python and their examples.
Example of Exceptions:
- Num1=5
- Num2=0;
- print(Num1/Num2)
Output: ZeroDivisionError: division by zero,
Output: TypeError: Can't convert 'int' object to str implicitly.
Output: NameError: name 'num' is not defined.
- import math
-
- math.exp(10000)
Output: OverflowError: math range error,
Output : ImportError: No module named 'foo'.
- array={'a':'1','b':'2'}
-
- array['c']
Output : KeyError: 'c'
- array = [1,2,3,4,5,6,7]
-
- array[10]
Output : IndexError: list index out of range.
So above all examples shows the exceptions in python programs with different-2 types.
So now I will tell you how to handle Exceptions
Example of Exception Handling:
try:
- num1=5
- num2=0
- print(num1/num2)
- except ZeroDivisionError:
- print("Divided By Zero")
Output : Divided by Zero
try:
- print("10"+6)
- except TypeError:
- print("Error occured in \"10\"+6")
Output : Error occured in "10"+6
try:
- print(2+4*num)
- except NameError:
- print("num is not define")
Output : num is not define
So many exception handlings can handle the above Examples.
Raising Exceptions:
The raise statement forces an indication of specified Exception to occur.
try:
- num1=5
- num2=0
- print(num1/num2)
- except ZeroDivisionError:
- raise ZeroDivisionError("Error Occured")
Output : Shown in below image
So the above example, Shows a raise statement and prints the error forcibly in except module.
Finally :
In any exception occurred in code finally statement always runs after the execution of the code in the try block
try:
- num1=5
- num2=0
- print(num1/num2)
- except ZeroDivisionError:
- print("Error Occured")
- finally:
- print("This code will run always")
Output: Error Occured
This code will run always.
So we can use the final statement in each exception for running always code in the final statement. I hope you will understand this part of the python programming language.