Exception Handling in Python

Exception is a run time error which occurs during the program execution.  Python provides in-built support for handling the runtime error using try-except block.

syntax:

try:
// code which may throw the exception
except:
// exception handler
finally:
// clean up code

try block contains the code which may throw the Exception. except block contains the Exception handler to handle the Exception. finally block code will be executed when the exception is raised or not raised.

Example 1
# Exception Handling
try:
a=int(input(“First Number: “))
b=int(input(“Second Number: “))
c=a/b
print (“Output:”, c)
except Exception:
print(“Number can’t be Divided by 0”)
finally:
print(“There may or may not have been an exception.”)

Note: Exception is built-in class which handles all types of exceptions in Python

Example 2: try with Multiple except block
try:
x = int(input(“Your number: “))
res = 15 / x
print(“Result – “, res)
except ValueError:
print(“You should have given either an character or a float”)
except ZeroDivisionError:
print(“Infinity”)

Note: one except block can handle only one type of exception. to catch more than one type of exception a try block can have multiple except block

Example – 3 try block with else block
try:
a=10/2
print (“Output : “, a)
except ZeroDivisionError:
print(“No. Cann’t be divieded by Zero”)
else:
print(“No Exception”)
Note: else block will be executed whenever there is no exception

Example – 4 try with raise keyword
try:
x=”a”
a=10/x
print (“Output : “, a)
except:
      raise # prints the type of Exception raised by the code

Win Corporate Training
website: http://www.wincorptrg.com
View My Profile

Advertisements