Flat 10% & upto 50% off + Free additional Courses. Hurry up!

Python Exception Handling


Exceptions are the events which can change the flow of control through a program. In Python, exceptions can be both intercepted and triggered by our programs. They are processed by two new statements:-

  • Try – Catches exceptions raised by Python or a program
  • Raise – Triggers an exception manually

In typical Python programs, exceptions may be used for a variety of things:

  • Error handling
  • Event notification
  • Special-case handling
  • Unusual control-flows


Exception Basics

These exceptions are the high-level control flow device. They exceptions may be raised either by python or by our programs. In these both cases try statement is used. Python try statements come in two types –

  • One that handles exceptions
  • Other that executes finalization code whether exceptions occur or not.



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


<statements> # run/call actions

except <name>:

<statements> # if 'name' raised during try block

except <name>, <data>:

<statements> # if 'name' raised; get extra data


<statements> # if no exception was raised
  • If an exception is occurred when the try block’s statements are running then python go back to the try block and runs those statements which comes under the first except clause and that matches the raised exception. Control continues past the entire try statement after the except block runs unless the except block raises another exception.
  • If an exception happens in the try block and no except clause is matched then exception is propagated up to a try or to the top level of the process.
  • When the statements under the try header run and no exception occurs then python runs the statement which comes under the else and then control is resumed past the whole try statement.


try /finally

When a finally 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 past the entire try statement.
  • If an exception does occur during the try block’s run, Python comes back and runs the finally block, but then propagates the exception to a higher try (or the top level); control doesn’t continue past the try statement.





<statements>  # always run “on the way out”



To trigger exceptions you need to code raise statements. Their general form is simple: the keyword raise followed by the name of the exception to be raised. You can also pass an extra data item (an object) along with the exception by listing it after the exception name. If extra data is passed then it can be caught in a try by listing an assignment target to receive it: except name, data:

raise <name> # manually trigger an exception

raise <name>, <data> # pass extra data to catcher too


def intellipaat(list, n):

print list[n] # trigger IndexError


intellipaat([0, 1, 2], 3)

except IndexError: # catch exception here

print "Hello world!"


Exception Catching Modes

  • try Statement Clauses

When you write try statements, a number of clauses can appear after try statement block.

Table: try Statement Clause Forms

 Clause Form    Interpretation
except: Catch all (other) exception types
except name: Catch a specific exception only
except name, value: Catch exception and its extra data
except (name1, name2): Catch any of the listed exceptions
else: Run block if no exceptions raised
finally: Always perform block


  • Catching 1-of-N Exceptions

When an exception is raised as the call to the action function is running then python returns to the try and finds for the first except that catches the exception raised. It checks except clauses from top to bottom and left to right and runs the statements under the first that matches. If no matches is found then the exception is propagated past this try; the else runs only when no exception occurred.



except NameError:


except IndexError


except KeyError:


except (AttributeError, TypeError, SyntaxError):





User Defined Functions

It is also known as custom exception. Python provides the facility to create your own exceptions class form the built in exceptions.


class userexecption(Exception):

def __init__(self, value):

self.value = value


raise userexecption("Error is occured")

except userexception,u:

print u.value


Error is occurred

This blog will help you get a better understanding of Automate Your Coding with Python!

"0 Responses on Python Exception Handling"

Training in Cities

Bangalore, Hyderabad, Chennai, Delhi, Kolkata, UK, London, Chicago, San Francisco, Dallas, Washington, New York, Orlando, Boston

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


Sales Offer

  • To avail this offer, enroll before 26th October 2016.
  • This offer cannot be combined with any other offer.
  • This offer is valid on selected courses only.
  • Please use coupon codes mentioned below to avail the offer
DW offer

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