Python Exception Handling Using try, except and finally Statements

Python provides different statements like try, except, finally, etc. in order to handle exceptions. When the Python application encounters a programmatic error it raises an exception and stops the application execution by default as there is no way to resume application execution. But this is a big problem as stopping application in every error is not a good idea which prevents the efficiency and may cause data loss.

Python Exception Example

As a first step, we define an exception scenario and create Python code that raises exceptions. We create a list that consists of 3 items but try to get the 5th item even it does not exist in the list.

cities = ["Ankara","Istanbul","Izmir"]

print(cities[4])

This code raises the following “IndexError”.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

Catch Python Exception with try

In the following example, we use the try keyword in order to catch the exception. The code parth which may raise an exception is put inside the try keyword body

cities = ["Ankara","Istanbul","Izmir"]

try:
  print(cities[4])
except Exception as e:
  print(e)

Catch Specific Exceptions with try and except

The Exception class provides generic exception objects but there may be different exception classes. In the following example, we use the IndexError exception class in order to handle the exception.

cities = ["Ankara","Istanbul","Izmir"]

try:
  print(cities[4])
except IndexError as e:
  print(e)

Raise Exception with raise

Python also provides the ability to raise an exception manually without an actual error. The raise statement is used to raise and create an exception. The exception can be raised by a generic exception class or a specific exception class.

cities = ["Ankara","Istanbul","Izmir"]

try:
  print("We raise an exception in the next line")
  raise Exception("This is exception")
except Exception as e:
  print(e)

Run Code After Exception with finally

In some cases, we may need to run some code even there is an exception. In this case, first, the exception should be handled with the try keyword and then we can use the finally statement in order to execute code after catching the exception.

cities = ["Ankara","Istanbul","Izmir"]

try:
  print(cities[4])
finally:
  print("There is an exception we end the application.")

Leave a Comment