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 developers 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:

  • What is an Error in Python?
    • Syntax error
    • Exceptions
      • Built-in exception classes
    • Exception handling
      • Try-except-else clause
      • Try-finally clause
      • Raise exceptions
    • Conflicts in exception handling

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

types of errors in python

Syntax Errors:

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

test = [1,2,3]
for i in test:
print(i)#here we have indentation errorOutput:
File “<ipython-input-8-c48e2cfe6fc1>”, 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:
#here we have indentation error
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 the generic cases.

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

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.

Wish to Learn Python? Click Here

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:

Process for handling Python exception

  • 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.

Become Python Certified in 16 hrs.


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” )Output:
So, let us close the file#exception block is not executed since 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:”,

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))output:
time= 0.07828223999999295
time= 0.0019908266666845975

Now that we have learnt how to deal with exceptions in our codes we are ready to get started with the advanced part of python. But before that let us learn some of the important python modules in our Python Tutorial Program. GO to next module learn more or check out our Python course to excel your carreer.

Previous Next

Download Interview Questions asked by top MNCs in 2018?

Learn SQL in 16 hrs from experts

"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.