Exception Handling Using Python
Exception Handling Using Python
HANDLING EXCEPTION
Exception
An Exception is an event which occurs during the execution of a program that disrupts the normal
flow of the program’s instructions. If a python script encounters a situation it cannot cope up, it
raises an exception
HOW TO HANDLE EXCEPTION?
There are four blocks which help to handle the exception. They are
try block
except statement
else block
finally block
i) try block
In the try block a programmer will write the suspicious code that may raise an
exception. One can defend their program from a run time error by placing the codes
inside the try block.
Syntax:
try:
#The operations here
except Exception 1:
#Handle Exception 1
except Exception 2:
#Handle Exception 2
finally:
#Always Execute
Syntax:
c) Argument of an Exception
An exception can have an argument which is a value that gives additional information
about the problem. The content of an argument will vary by the exception.
d) Raising an Exception
You can raise exceptions in several ways by using raise statement
Syntax:
Example:
TYPES OF EXCEPTION
There are two types of Exception:
Built-in Exception
User Defined Exception
i) Built-in Exception
There are some built-in exceptions which should not be changed.
The Syntax for all Built-in Exception
except Exception_Name
ASSERTION
An assertion is a sanity check which can turn on (or) turn off when the program is in testing mode.
The assertion can be used by assert keyword. It will check whether the input is valid and
after the operation it will check for valid output.
Syntax:
assert(Expression)