Exception Handling is one of the core feature of any programming language including Python. Python makes it very easy to handle exceptions which might occur during the execution of a program or application.
Try-Except-Else-Finally: Skeleton of Exception Handling
Straight to the point, below is a skeleton of exception handling blocks in Python.
There are four blocks, namely,
finally, are described below.
- try block contains the part of the code which might generate exceptions.
- except block will
catchthe exception, if any, is generated.
- else block is executed when no exception is raised and program follows the normal flow of execution
- finally block is always executed and is normally used to release resources like opened file objects, thread locks etc.
The last two blocks,
finally are optional and can be removed if required, that is, we can just use
except block without the other two blocks.
Flow of execution
There are two cases to be considered here.
- Exception is raised: In this scenario,
try-except-finallyblock gets executed
- Exception is not raised:In this scenario,
try-else-finallyblock gets executed
In simpler words, these are main points to note here.
tryblock always gets executed (obviously)
exceptblock is executed if exception is raised, otherwise
elseblock gets executed.
finallyblock is always executed
Look at the example below.
The first call to
add function does not raise any exception and therefore
try-else-finally block is executed while the second call does raise an error (type-mismatch, integer and string) leading to execution of
Handling Specific Exceptions
All of examples described below is
catch-all exception in
except block. Sometimes, you may want to handle each types of exception separately.
The idea here is to use multiple
except blocks for each type of exceptions followed by your
catch-all except block at the end.
In some cases, we don't want do anything if an exception is raised. In such cases, we can just
pass in the
We can manually raise exceptions using
Nested Try Block
We can nest one
try block into another.
We covered the fundamental of exception handling in Python. We displayed how easy it is in Python to write and programs which handles exceptions efficiently.