Tutorials  Articles  Notifications  Login  Signup


Rajan Kumar

Founder at HackersFriend Updated July 21, 2020, 11:11 p.m. ⋅ 1589 views

Handling Exceptions in Python

We often encounter situations where we want to see the exact error message, to understand what went wrong with our code.

This is much needed when our code base is huge and it becomes very hard to guess where error might have happened. We also, need to catch exceptions to handle different use cases of of any feature or piece of code. In this article, I'll show you how you can catch the exception.

Catching exception in Python

To handle exceptions in python, we can use Python's inbuilt exception handling.

We'll have to put the block of code which is expected to have any exceptions, inside Try, and then we'll have to handle it's exception in Except block.


We can also have a Finally block, this block will be executed irrespective of exceptions.

  •  Try - lets you test a block of code for errors.
  • Except - block lets you handle the error.
  • Finally - block lets you execute code, regardless of the result of the try- and except blocks.

 Have a look at the following example.


except NameError:
  print("Variable x is not defined, so NameError raised.")

  print("Something else went wrong")

  print("The 'try except' is finished")


Else in exception handling

We can also use else, in exception handling, this will be executed, if no exception occurs.

Have a look at following piece of code.

  print("Hey there")
  print("Something went wrong")
  print("Nothing went wrong")

Raising an exception

We can also raise an exception in python and handle it in except block.

Have a look at following piece of code.

x = -10

if x < 0:
  raise Exception("Oops. The number was below 0")

We can also raise any specific type of exception.

x = "Hey"

if not type(x) is int:
  raise TypeError("TypeError - Value is not an Integer")

Printing exceptions

We can print messages of exceptions also.

    l = [1, 2, 3]

except IndexError e:
list index out of range


Image credits: Image by Michael Schwarzenberger from Pixabay

HackerFriend Logo

Join the community of 1 Lakh+ Developers

Create a free account and get access to tutorials, jobs, hackathons, developer events and neatly written articles.

Create a free account