Exception Handling in Python
eeeC
CEC-Swayam Course on Programming in Python
Exception
Unexpected Response of the Program
Error Exception
Logical Syntactic Synchronous Asynchronous
Error Error
•DividebyzeroError
Common •NameError
Exceptions •IndentationError
•IOError
•EOFError
Exception
• An exception is a runtime event i.e. which occurs during the
program execution, and it disrupts the normal execution of the
program.
• An exception is raised by a program if it encounters a situation
that it cannot deal with.
• If an exception is raised by a program it must be handled else the
program will terminate its execution with an error message.
• Let's see some examples.
Handling exceptions
The try-except block
try:
Block of
statements
except ExceptionName: Block of
statements
Multiple exception
try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code
…...................
Single block multiple exception
try:
#block of code
except (<Exception 1>,<Exception 2>,<Exception 3>,....<
Exception n>)
#block of code
Exception Handling in Python
PART II
Except block without exception
try:
#block of code
except:
#block of code
else clause
try:
#block of code
except :
#block of code
else:
#block of code
The finally block
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 occurred or not
Raising Exception
Syntax:
raise [exception [,args [,traceback]]]
Thank you