Exception Handling in Python

Still getting Runtime Error | Exception Handling in Python | 10 mins read

Table of Contents

Table of Contents

Introduction

Good to Go

Hello, and welcome back to another exciting tutorial.Today, we are going to talk about “Exception Handling in Python“. This tutorial covers:-

  • Meaning of Exception
  • Try,Catch ,Else and Finally Block
  • How to raise an exception in python
  • Understanding builtin exceptions
  • Examples regarding above topics for better understanding

If you aren’t following along, I would recommend you to go back where you left or start from here.

Why we need exception handling in Python ?

Good to Go

The flow of execution of the program can be disrupt by errors or exceptions.

ErrorsMainly consists of syntax errors and can be detected at compile time.Hence ,easy to resolve.

For example,

for i in range(10)
print("Hi , I am Harry")
#Output
File "", line 1
for i in range(10)
^
SyntaxError: invalid syntax

The above code tries to create a loop with the wrong syntax .Hence the compiler throws the syntax error .You can find the correct way of declaring a loop here.

Exceptions -Errors detected at run time are called exceptions. For example,

print(1/0)
#Output
Traceback (most recent call last):
File "", line 1, in
ZeroDivisionError: division by zero
print('HI'+ 1)
#Output
Traceback (most recent call last):
File "", line 1, in
TypeError: can only concatenate str (not "int") to str

Exception Handling in Python

The execution must go on

Exception Handling in Python

The exceptions disrupts the flow of program. If a non-technical person is using your product ,it might be difficult for him to understand the technical terms raised by compiler during exception.

As a programmer, it is our duty to foresee these situations and handle them efficiently. Let us understand the mechanism for exception handling in python.

try

All the code which is prone to any exception is written under try block.

How it works?

  • The flow of program enters the try block.
  • If any exception occurs,
    • rest of code in the try block is ignored and flow is passed to the except block.
    • if no except block is found, it becomes an unhandled exception and execution stops with error shown above.
  • If no exception occurs,except block is ignored.

Except

All the exceptions raised in try block are handled in this block.

A try block can have more than one except block to customize response for different exceptions.

How it works?

  • An exception is raised in the try block.
  • The program search for the first except block that matches the exception.

Examples:-

  • One except block that handles all types of exceptions
    • This is an easy but poor way to handle the exception as you wouldn’t be sure which part in the code trigger the exception.
>>> try:
...     print(1/0)
... except:
...     print('Some exception occurs!!!')
... 
Some exception occurs!!!
>>> 
  • Except block with type of error to handle
    • This method is more effective than the previous one. Still, there are chances that an error may occur that is not handled by customized except block.
>>> try:
...     print(1/0)
... except ZeroDivisionError:
...     print('Somewhere you have divided a number with zero')
... 
Somewhere you have divided a number with zero
>>> 
  • Multiple except block
    • The multiple except block is executed one by one until the first match found.
>>> try:
...     print(1/0)
... except TypeError:
...     print('Mismatched Type!!')
... except ZeroDivisionError:
...     print('Somewhere you divided a number with zero')
... 
Somewhere you divided a number with zero
>>> 
  • Except block with more than one error to handle
    • The except block can take multiple errors to handle as parenthesized tuple. This strategy is suitable if you want to handle a group of error in a certain way.
>>> try:
...     print('Hi' + 5)
... except (ZeroDivisionError,TypeError):
...     print("Either divion by zero happened or type mismatched for operand")
... 
Either divion by zero happened or type mismatched for operand

else

  • This block executes if no exception occur in the try block.
  • It is optional to include this block.
  • It is useful to include when you want to executes the code other than normal program flow.

For example:-

  • Else block will executes as there is no exception.
>>> try:
...     print("Try block with no exceptions")
... except:
...     print("Print this if any exception occurs")
... else:
...     print("Print this if no exception occurs")
... 
Try block with no exceptions
Print this if no exception occurs
>>> 
  • Else block will not executes in case of exception.
>>> try:
...     print('Hi'+5)
... except:
...     print("Type mismatched for operands")
... else:
...     print("Surprise!! No error")
... 
Type mismatched for operands
>>> 

finally

  • This block always executes.
  • It is optional to include this block.
  • It is useful when you want to include some message or clean up task before exiting the try block statements.

For example:-

Lets define all four blocks try,except,else and finally for a simple divide function.

def divide(a,b):
"""Function that divides a with b and print the result"""
try:
res = a//b
except ZeroDivisionError:
print("Cannot divide a number with zero")
else:
print(f"{a} divides by {b} equals {res}")
finally:
print("Function completed!!")
  • When no exception raised
divide(8,4)
#Output
8 divides by 4 equals 2
Function completed!!
  • When exception is raised
divide(8,0)
#Output
Cannot divide a number with zero
Function completed!!

There are some builtin exceptions with associated value defining the cause of error. You can find them here

How to raise exception in Python

Create your own

With the help of raise keyword, we can force an exception to occur.

For example, Suppose we have an add function which takes two integer and return their sum or raise TypeError if datatype other than int is passed as parameters.

def add(a,b):
"""Function that adds two integers a and b or raise TypeError for other types"""
if(type(a)!= int or type(b)!=int):
raise TypeError('Parameters must be of integer type')
print(a+b)
  • When no exception raised
add(8,0)
#Output
8
  • When exception is raised
add(8.5,0)
#Output
Traceback (most recent call last):
File "/home/main.py", line 7, in 
add(8.5,0)
File "/home/main.py", line 4, in add
raise TypeError('Parameters must be of integer type')
TypeError: Parameters must be of integer type

How to create new exception in Python

Create your own

All the exceptions are derived from a base class in python i.e. Exception. To create a new exception, we have to create a new class which inherits Exception class.

For example,

class EvenNumberError(Exception):
"""Exception raised for errors in the given number.
Attributes:
message -- explanation of the error
"""
def __init__(self,message="Number must not be even"):
self.message = message
super().__init__(self.message)
number = 2
if number%2 == 0:
raise EvenNumberError
#Output
Traceback (most recent call last):
File "/home/main.py", line 14, in 
raise EvenNumberError
__main__.EvenNumberError: Number must not be even

To further add more functionality to this Exception class, you need to have basic understanding of Object Oriented Programming in python. Read our detailed tutorial on OOPs for better understanding.

Conclusion .

Now , you are familiar with exception handling in python. I hope buzz words like try,except,else,finally and raise should be clear to you. Implement this knowledge in your code to make it fail safe.

Do leave your feedback and suggestions. We would love to hear your feedback.

Till then , keep coding.