Exception Handling
Handling exceptions using try-except-finally blocks
Exception
It is a type of error that occurs at run time
An exception is a Python object that represents an error
Example
a=input(“Enter a number”)
x=a/5
print(x)
Enter a number 45
TypeError : unsupported operand type(s) for ‘str’ and ‘int’
Types of exception
Some of the commonly occurring built-in exceptions are
SyntaxError, ValueError, IOError, KeyboardInterrupt, ImportError,
EOFError, ZeroDivisionError, IndexError, NameError, IndentationError,
TypeError, OverFlowerror.
Exception Handling – Catching the exception and giving the appropriate response
to the user in simple message instead of technical error message is called
exception handling
Component of Exception Handling-
try ,except, else, finally blocks
try-An exception is caught in the try block. It is error prone code
except-It handles the exception
else-if there is no exception in code
finally-The statements inside the finally block are always executed regardless of
whether an exception occurred in the try block or not.
Example (i)
Without using try except block
a=input(“Enter a number”)
x=a/5
print(x)
Run:
Enter a number 45
TypeError : unsupported operand type(s) for ‘str’ and ‘int’
Using try except block
a=input(“Enter a nimber”)
try:
x=a/5
except TypeError
print(“ Invalid Input Type”)
else:
print(x)
finally:
print(“Thank you”)
Run:
Enter a number 45
Invalid Input type
Thank you
Example (ii)
Without using try except block
a=int(input(“Enter a number”))
b=int(input(“Enter a number”))
x=a/b
print(x)
Run:
Enter a number 5
Enter a number 0
x=a/b
ZerDivisionError: division by zero
Using try except block
a=int(input(“Enter a number”))
b=int(input(“Enter a number”))
try:
x=a/b
except ZeroDivisionError:
print(“Don’t Input zero”)
else:
print(x)
finally:
print(“Thank You”)
Run:
Enter a number 5
Enter a number 0
Don’t Input zero
Thank you
Run:
Enter a number 5
Enter a number 2
2.5
Thank you
Question 7- Page 17 - Chapter 1 Exception Handling in Python ( NCERT )
Ans.
print (" Learning Exceptions...")
try:
num1= int(input (" Enter the first number")
num2=int(input("Enter the second number"))
quotient=(num1/num2)
print ("Both the numbers entered were correct")
except ValueError_: # to enter only integers
print (" Please enter only numbers")
except ZeroDivisionError : # Denominator should not be zero
print(" Number 2 should not be zero")
else:
print(" Great .. you are a good programmer")
finally : # to be executed at the end
print(" JOB OVER... GO GET SOME REST")