Lecture-47 (Exception Handling)
Lecture-47 (Exception Handling)
Lecture-47 (Exception Handling)
LECTURE 47
Today’s Agenda
• Exception Handling
try
except
else
raise
finally
Exception Handling Syntax
try: Remember !
In place of Exception I and
You do your operations here; Exception II , we have to use
the names of Exception
......................
classes in Python
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Improved Version
Of Previous Code
Example:
A try statement may have more than one except clause for
different exceptions.
import math
try:
x=10/5
print(x)
ans=math.exp(3)
print(ans)
except ZeroDivisionError:
print("Division by 0 exception occurred!")
except ArithmeticError:
print("Numeric calculation failed!")
Output:
Guess The Output !
import math
try:
x=10/0
print(x)
ans=math.exp(20000)
print(ans)
except ZeroDivisionError:
print("Division by 0 exception occurred!")
except ArithmeticError:
print("Numeric calculation failed!")
Output:
Guess The Output !
import math
try:
x=10/5
print(x)
ans=math.exp(20000)
print(ans)
except ZeroDivisionError:
print("Division by 0 exception occurred!")
except ArithmeticError:
print("Numeric calculation failed!")
Output:
Guess The Output !
import math
try:
x=10/5
print(x)
ans=math.exp(20000)
print(ans)
except ArithmeticError:
print("Numeric calculation failed!")
except ZeroDivisionError:
print("Division by 0 exception occurred!")
Output:
Guess The Output !
import math
try:
x=10/0
print(x)
ans=math.exp(20000)
print(ans)
except ArithmeticError:
print("Numeric calculation failed!")
except ZeroDivisionError:
print("Division by 0 exception occurred!")
Output:
Exercise
If the user enters a non integer value then ask him to enter only integers
If denominator is 0 , then ask him to input non-zero denominator
Repeat the process until correct input is given
Only if the inputs are correct then display their division and
terminate the code
Sample Output
Solution
while(True):
try:
a=int(input("Input first no:"))
b=int(input("Input second no:"))
c=a/b
print("Div is ",c)
break;
except ValueError:
print("Please input integers only! Try again")
except ZeroDivisionError:
print("Please input non-zero denominator")
Single except,
Multiple Exception
while(True):
try:
a=int(input("Input first no:"))
b=int(input("Input second no:"))
c=a/b
print("Div is ",c)
break;
except (ValueError,ZeroDivisionError):
print("Either input is incorrect or denominator is 0. Try
again!")
Sample Output
Handling All Exceptions
The only problem will be that we will never know the type
of exception that has occurred!
Exception Handling Syntax
while(True):
try:
a=int(input("Input first no:"))
b=int(input("Input second no:"))
c=a/b
print("Div is ",c)
break;
except:
print("Some problem occurred. Try again!")
Sample Output