Try-Except-Else-Finally blocks in Python

Try except block in Python is used to handle run time errors. There are some pre-defined exceptions in Python, few of them are;

  • ArithmeticError
  • EOFError
  • IndexError
  • ValueError
  • ImportError

We can also create our own exceptions(custom exceptions).

Let's first understand how we can write try-except block in Python programming.

Try-Except-Else-Finally blocks in Python

As shown in the above image, we used to write try-except block.

*Note: As we know, indentations(spaces) are very important in python programming.

In Python, we have an else block as well and it will execute if except block will not. In simple words, if the try block execute successfully then only the else block will execute.

Try-Except-Else-Finally blocks in Python

In the above code, as we can see try and else block executed and returned the message. That means except block was not executed. But in case there are some errors occur and except block comes into the picture then else will not execute here.

Try-Except-Else-Finally blocks in Python

Now moving to the finally block. Like in other languages, we have finally block in Python and it will execute at any cost. 

Try-Except-Else-Finally blocks in Python

Try-Except-Else-Finally blocks in Python

As you can see in the above code snipped, finally block executed either try executed or except.

Here question can comes to our mind like what is the use of the finally block if it is executed in each scenario?

The answer is; it totally depends on our requirements. Suppose we have to log events or we need to close connections after code execution so we can use the finally block here and do what we want to do.

Can we use multiple try except block in our code?

Yes, we can use multiple try except block in Python like other programming languages.

Try-Except-Else-Finally blocks in Python

As shown in the above code snipped, here we used nested try-except block, and the code executed successfully.

Now next question can come to our mind, can we use try-except block inside except block or else block or finally block? So the answer is Yes.

Try-Except-Else-Finally blocks in Python

Try-Except-Else-Finally blocks in Python

I hope try-except block is more clear from a theoretical and coding perspective.

 

Next Recommended Reading Middleware In Fast API Python