Flat 10% & upto 50% off + 10% Cashback + Free additional Courses. Hurry up
  • Live Instructor-led Classes
  • Expert Education
  • 24*7 Support
  • Flexible Schedule

Exception Handling

It is obvious for a developer to encounter a few errors or mistakes in their code file. But what if developers could minimize their mistakes or error, wouldn’t it be great? Python offers Exception handling methods, which helps developers deal with potential errors and mistakes.

In this tutorial we will be discussing the below-given topics:

So without any further delay, let’s get started.

Learn Python in 16 hrs from experts

What is an Error in Python?

Before discussing how to deal with errors, let us try to understand what errors in Python are.   Errors in python are nothing but mistakes in the code which are potentially harmful.

There are two types of errors in python.

  • Syntax Errors,
  • Exceptions

What is an error

Syntax Errors

Syntax Errors are nothing but errors that are caused while writing the code structure.

test = [1,2,3]
test = [1,2,3]
for i in test:


File “”, line 3
IndentationError: expected an indented block


Exceptions are nothing but errors which are encountered at runtime


test = [1,2,3]
for i in test:


File “”, line 3
Indentation Error: expected an indented block

Some built-in exception classes:

These are some of the built-in exception classes that are already defined for generic cases.

Exception ClassEvent
IOErrorIt gets raised when an input/ output operation fails
Arithmetic ErrorIt gets raised  when numeric calculations fail
Floating Point ErrorIt gets raised  when a floating-point calculation fails
Zero Division ErrorIt gets raised  when division or modulo by zero takes place for all numeric types
Assertion ErrorIt gets raised  when the assert statement fails
Overflow ErrorIt gets raised  when result of an arithmetic operation is too large to be represented
Import ErrorIt gets raised  when the imported module is not found
Index ErrorIt gets raised  when index of a sequence is out of range
Keyboard InterruptIt gets raised  when the user interrupts program execution, usually by pressing (Ctrl+c)
Indentation ErrorIt gets raised  when there is incorrect indentation
Syntax ErrorIt gets raised  by parser when syntax error is encountered
Key ErrorIt gets raised  when the specified key is not found in the dictionary
Name ErrorIt gets raised  when an identifier is not found in the local or global namespace
Type ErrorIt gets raised  when a function or operation is applied to an object of incorrect type
Value ErrorIt gets raised  when a function gets argument of correct type but improper value
Runtime ErrorIt gets raised  when a generated error does not fall into any category

Wish to Learn Python? Click Here

Exception Handling

In Python, exceptions can be handled by two new methods:-

  • Try – Catches exceptions raised by Python or a program
  • Raise – a Custom exception which triggers an exception manually.

Try-except-else clause

It initiates with a try header line which is followed by a block of indented statements than one or more optional except clauses and then at the end an optional else clause like as follows:

Your statements
except Exception_1:
If there is Exception_1 then execute this block- statement
except Exception_2:
If there is Exception_2 then execute this block-statement
if no exception was raised-statement

Now let us understand that with an example:

fp = open(‘myfile.txt’)
line = f.readline()
i = int(s.strip())
except (IOError,ValueError) as e:
print (“check if the file is read-only.”,e.errno)
print (“Unexpected error”)

What exactly is happening here?

Say a chunk of code is written inside the try block that is suspected to raise an exception. Then to handle that exception we write exception block.

The handling process:

try except else clause

  • First, try block is executed
  • Case-1: If no exception occurs, except blocks are skipped then starts executing the else block.
  • Case-2: If an exception occurs during the execution of try block, rest of the executing is stopped. Then, look for matching exception handling block.
    • If found: Execute that exception block, after the exception is handled, execute rest of the try statement.
    • If not found: Stop the whole execution with an error message.

Note: Remember that python can handle any number of exception.

Try-finally clause

When a final clause is used in a try then its block of statements is always run by Python whether an exception occurred while the try block was running or not:

  • If no exception occurs, Python runs the try block, then the finally block and then continues execution the rest.
  • If an exception does occur during execution of the try block, Python starts executing the finally block, but then propagates the execution to the except block to handle the exception.


fp = open(“test.txt”, “w”)
fp.write(“Test is not there”)
print (“So, let us close the file”)
except IOError:
print (“Error: File not found” )


So, let us close the file

I hope you have noticed that exception block is not executed. That is because file gets closed after the execution of the finally block.

Raise exceptions

To trigger exceptions, you need to code raise statements. Their general form is simple: the keyword raises followed by the name of the exception to be raised.


class RaisingValueError(Exception):
def __init__(self, data): = data
def __str__(self):
return repr( = int(input(“Enter Total Movies Seen: “))
Num_of_genres = int(input(“Enter Num of genres: “))
if(Num_of_genres < 1):
raise RaisingValueError(“Number of genres can’t be less than 1”)
except RaisingValueError as e:
print (“Try entering again:”,

Become Python Certified in 16 hrs.

Conflicts in Exception Handling:

Yes, it does make our codes robust and secures from the potential errors, but exception handling has a side effect too.
There are two types of errors in python.

  • Programs using try-except to handle exception will run slightly slower.
  • The size of your code will also increase.

Therefore, we should use exceptions when we are unsure of certain part of the code, not for normal error handling cases. This can be viewed with the help of an example as well.

import timeit
statement_1 = ”’\
except ZeroDivisionError:
satement_2 = ”’\
if any !=0:
print(“time for statement_1=”,timeit.timeit(stmt1,setup,number=100000))
print(“time for statement_2=”,timeit.timeit(stmt2,setup,number=100000))


time= 0.07828223999999295
time= 0.0019908266666845975

Now that we have learned how to deal with exceptions in our codes, we are ready to get started with the advanced part of python. The next module highlights Python Enumerate. See you there!

Previous Next

Download Interview Questions asked by top MNCs in 2018?

"0 Responses on Python Exception Handling"

    Leave a Message

    100% Secure Payments. All major credit & debit cards accepted Or Pay by Paypal.

    Sales Offer

    Sign Up or Login to view the Free Python Exception Handling.