Python Exception Handling


What is an Exception?

Exception is the error that can occur during the execution of the code. For Example, if we try to divide the number by zero, we will get an error.

When we are running our code, we can have errors like:

  1. Syntax Errors : Errors because the syntax of the code is not properly followed. Example, improper use of whitespace or tab. This type of error occurs during the compilation of code.
  2. Exceptions : Unexpected errors mostly because of something wrong with logic. Example, dividing a number by zero, trying to access an invalid index position of a list, etc. These types of errors occur during the execution of the code.

Example of exception.

In [1]:
a = 1
b = 0
a/b
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-1-b6249a4a2b4f> in <module>
      1 a = 1
      2 b = 0
----> 3 a/b

ZeroDivisionError: division by zero

Exception stop execution

Whenever we have an exception in our code, it will stop the execution of the code. Means, it will stop the program in between itself.

You can see that the print statement will not execute because of error at line 3.

In [1]:
a = 1
b = 0
a/b
print("Thanks for visiting")
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-1-92035bc7aaa3> in <module>
      1 a = 1
      2 b = 0
----> 3 a/b
      4 print("Thanks for visiting")

ZeroDivisionError: division by zero

What is Exception Handling

Exception handling is the way to handle run time errors in a much more graceful way, which will not stop the further execution of the code.

In Python, to handle the exception, we use the try except statement.

Try Except – Catch Exceptions

Try block is the place where we write our original code that, we think, can throw an exception. Except block is supposed to follow the try block where control will jump to exception/error.

We are able to handle the error in much graceful way.
Instead of divide by zero error we just got the line mentioned in the except block as error.

In [1]:
try:
    a = 1
    b = 0
    a/b
except:
    print("There is some issue with code")
There is some issue with code

The print statement after the except block will also execute. So now further execution of code is not blocked.

In [2]:
try:
    a = 1
    b = 0
    a/b
except:
    print("There is some issue with code")
print("Thanks for visiting")
There is some issue with code
Thanks for visiting

Try Except with Else

Along with the try except block, we can add the else block, which will execute only after complete execution of the try block. If try block gets interrupted in between because of some exception, then else block will not be executed.

The else block will not execute because try block raised exception.

In [1]:
try:
    a = 1
    b = 0
    a/b
except:
    print("There is an exception in the code.")
else:
    print("This will execute only if try will completely execute.")
There is an exception in the code.

This time else block will execute because there is no exception in the try block.

In [2]:
try:
    a = 1
    b = 2
    a/b
except:
    print("There is an exception in the code.")
else:
    print("This will execute only if try will completely execute.")
This will execute only if try will completely execute.

Try Except with Finally

We can add the finally block with the try except block or with the try except else block. Finally block will always get executed irrespective of if try block gets interrupted because of some error or not.

Here try block will raise an exceptoin but finally will still get executed.

In [1]:
try:
    a = 1
    b = 0
    a/b
except:
    print("There is an exception in the code.")
finally:
    print("This will execute for the sure.")
There is an exception in the code.
This will execute for the sure.

Here try block will not raise any exception so both else and finally will get executed.

In [2]:
try:
    a = 1
    b = 2
    a/b
except Exception as e:
    print("There is an exception in the code.")
else:
    print("This will execute only if try will completely execute.")
finally:
    print("This will execute for the sure.")
This will execute only if try will completely execute.
This will execute for the sure.