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.
try:
print(x)
except NameError:
print("Variable x is not defined, so NameError raised.")
except:
print("Something else went wrong")
finally:
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.
try:
print("Hey there")
except:
print("Something went wrong")
else:
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.
try:
l = [1, 2, 3]
l[4]
except IndexError e:
print(e)
list index out of range
Image credits: Image by Michael Schwarzenberger from Pixabay