Exceptions
are categorized into two categories. They are –
1. Pre-defined Exceptions – The runtime
errors representation class which are present in python software are known as
pre-defined exceptions. Example – value error, zero division error, key error, index error, name error etc.
Pre-defined exceptions raised automatically whenever corresponding runtime
error is occurred. After raising the pre-defined exceptions programmers handle
those exceptions by using try and except blocks.
2. User defined Exceptions – The runtime
errors representation which are defined by the programmers explicitly according
to their business requirements are known as user defined exceptions. Any user
defined class which is extending any one of the pre-defined exceptions class is
known as a user defined exception class.
Syntax –
class classname(predefined
exception classname)
----------
----------
----------
User
defined exceptions will not raise automatically so that we have to rise those
exceptions explicitly.
Note – Creating the runtime
error representation class object is known as raising the exception.
We can
raise the exceptions explicitly by using raise
keyword.
Syntax – raise userdefinedexception
Note – We can also raise the
pre-defined exceptions explicitly by using raise keyword.
After
raising the exception we can handle that exception using try and except blocks.
Example –
class Error(Exception) :
""" Base class for other exceptions """
pass
class valueTooSmallError(Error):
""" Raised when the input value is too large"""
pass
class valueTooLargeError(Error):
""" Raised when the input value is too small"""
pass
num=10
while True:
try :
i_num=input('Enter a number : ')
if i_num<num:
raise valueTooSmallError
elif i_num>num :
raise valueTooLargeError
break
except valueTooSmallError:
print 'This value is too small, please try again'
except valueTooLargeError:
print 'This value is too large, please try again'
print 'Congratulation, at last you successfully succeeded'
Output –
Enter a
number : 8
This
value is too small, please try again
Enter a
number : 12
This
value is too large, please try again
Enter a
number : 10
Congratulation,
at last you successfully succeeded
No comments:
Post a Comment