Demo Exceptions
Demo Exceptions
try :
#statements in try block
except :
#executed when error in try block
ex:
try:
a=5
b='0'
print(a/b)
except:
print('Some error occurred.')
print("Out of try except blocks.")
===
try:
a=5
b='0'
print(a+b)
except TypeError:
print('TypeError Occurred')
except:
print('Some error occurred.')
print ("Out of try except blocks")
======
try:
a=5
b='0'
print(a+b)
except:
print('Some error occurred.') #except: before other blocks
except TypeError:
print('TypeError Occurred')
print ("Out of try except blocks")
========
multiple except:
try:
a=5
b=0
print (a/b)
except TypeError:
print('Unsupported operation')
except ZeroDivisionError:
print ('Division by zero not allowed')
except:
print('Some error occurred.')
print ('Out of try except blocks')
==========
else and finally
In Python, keywords else and finally can also be used along with the try and except
clauses. While the except block is executed if the exception occurs inside the try
block, the else block gets processed if the try block is found to be exception
free.
Syntax:
try:
#statements in try block
except:
#executed when error in try block
else:
#executed if try block is error-free
finally:
#executed irrespective of exception occured or not
=========
try:
x,y = 10, 2
z=x/y
except ZeroDivisionError:
print("except ZeroDivisionError block")
print("Division by 0 not accepted")
except:
print('Some error occurred.')
else:
print("Division = ", z)
finally:
print("Executing finally block")
x=0
y=0
print ("Out of try, except, else and finally blocks." )
==============
try:
x,y = 10, 0
z=x/y
except ZeroDivisionError:
print("Cannot devide by zero. Try again")
print("Division by 0 not accepted")
except:
print('Some error occurred.')
else:
print("Division = ", z)
finally:
print("Executing finally block")
x=0
y=0
print ("Out of try, except, else and finally blocks." )
==============
try:
x,y = 10, "xyz"
z=x/y
except ZeroDivisionError:
print("except ZeroDivisionError block")
print("Division by 0 not accepted")
except:
print('Error occurred.')
else:
print("Division = ", z)
finally:
print("Executing finally block")
x=0
y=0
print ("Out of try, except, else and finally blocks." )
=============
Raise an Exception
Python also provides the raise keyword to be used in the context of exception
handling. It causes an exception to be generated explicitly. Built-in errors are
raised implicitly. However, a built-in or custom exception can be forced during
execution.
The following code accepts a number from the user. The try block raises a
ValueError exception if the number is outside the allowed range.
Output
50.0 is out of allowed range
====