Exception Handling in Python

Introduction

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.

We have skipped discussion about what exceptions are since Python for Developers Course is targeted for developers who already has some programming experiences and know the basic of exception handling.

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, try, except, else and finally, are described below.

  • try block contains the part of the code which might generate exceptions.
  • except block will catch the 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, else and finally are optional and can be removed if required, that is, we can just use try and except block without the other two blocks.

Flow of execution

There are two cases to be considered here.

  1. Exception is raised: In this scenario, try-except-finally block gets executed
  2. Exception is not raised:In this scenario, try-else-finally block gets executed

In simpler words, these are main points to note here.

  1. try block always gets executed (obviously)
  2. except block is executed if exception is raised, otherwise else block gets executed.
  3. finally block is always executed

Basic Example

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 try-except-finally block.

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.

Ignore Exception

In some cases, we don't want do anything if an exception is raised. In such cases, we can just pass in the except block.

Raising Exceptions

We can manually raise exceptions using raise keyword.

Nested Try Block

We can nest one try block into another.

Conclusion

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.

Author image
New Delhi
I am a passionate programmer based in New Delhi, India. I mostly work with Python. Apart from work, I find myself doing poetry and learning about various languages. I prefer chai over coffee.