Python Exception Handling: A Quick Guide for Learning

Read this tutorial to learn Python exception handling. It should help you understand how to use try, except and finally statements in your programs. Go through the examples given to get started quickly.

Exception handling is very critical for creating robust and stable applications. And it encourages programmers to write clean, readable and error-free code.

You would agree that even the best of the code could behave unexpectedly at runtime. It could be due to a missing configuration, or a change in the execution environment or the user entered the wrong input.

Some of these errors may cause the program to terminate abruptly. With the help of Python exception handling, we can manage the above issues and avoid intermittent failures of our code.

Table of Content

First of all, we have to understand the difference between an error and the exception. Consequently, we’ll teach you the essentials of Python exception handling.

Python Exception Handling: Error vs. Exception

What is Error?

The error is something that goes wrong in the program, e.g., like a syntactical error.

It occurs at compile time. Let’s see an example.

if a<5
File "<interactive input>", line 1
    if a < 5
SyntaxError: invalid syntax

What is Exception?

The errors also occur at runtime, and we know them as exceptions. An exception is an event which occurs during the execution of a program and disrupts the normal flow of the program’s instructions.

In general, when a Python script encounters an error situation that it can’t cope with, it raises an exception.

When a Python script raises an exception, it creates an exception object.

Usually, the script handles the exception immediately. If it doesn’t do so, then the program will terminate and print a traceback to the error along with its whereabouts.

>>> 1 / 0
Traceback (most recent call last):
 File "<string>", line 301, in run code
 File "<interactive input>", line 1, in <module>
ZeroDivisionError: division by zero

How to Handle Exceptions with Try-Except?

What is Try-Except Statement?

We use the try-except statement to enable exception handling in Python programs.

Inside the try block, you write the code which can raise an exception.

And the code that handles or catches the exception, we place in the except clause.

Python Exception Handling Syntax

Following is the syntax of a Python try-except-else block.

	You do your operations here;
except ExceptionI:
	If there is ExceptionI, then execute this block.
except ExceptionII:
	If there is ExceptionII, then execute this block.
	If there is no exception then execute this block.

Have a look – 30 Python Interview Questions for Beginners.

Here is a checklist for using the Python try statement effectively.

  • A single try statement can have multiple except statements depending on the requirement. In this case, a try block contains statements that can throw different types of exceptions.
  • We can also add a generic except clause which can handle all possible types of exceptions.
  • We can even include an else clause after the except clause. The instructions in the else block will execute if the code in the try block doesn’t raise an exception.

Python Exception Handling Examples

Let’s take a sample code to understand the use of Python try-except.

   fob = open("test", "w")
   fob.write("This is my test file for exception handling!!")
except IOError:
   print "Error: can\'t find the file or read data"
   print "Write operation is performed successfully on the file"

The above code produces the following output.

>>Write operation is performed successfully on the file.

Let’s take another example in which we are trying to open a file in the READ mode.

We’ll perform a WRITE operation on it. Upon execution, it’ll throw an exception.

   fob = open("test", "r")
   fob.write("It's my test file to verify exception handling in Python!!")
except IOError:
   print "Error: can\'t find the file or read data"
   print "Write operation is performed successfully on the file"

The above code produces the following output.

>>Error: can't find file or read data

Handling All Types of Exceptions with Except

If we use a bare “except” clause, then it would catch all types of exceptions.

However, neither it’s a good programming practice nor does anyone recommend it.

It is because that such a Python try-except block can handle all types of exceptions. But it’ll not help the programmer to find what exception caused the issue.

You can go through the below code to see how to catch all exceptions.


   You do your operations here;
   If there is any exception, then execute this block.
   If there is no exception then execute this block.

Handling Multiple Exceptions with Except

We can define multiple exceptions with the same except clause. It means that if the Python interpreter finds a matching exception, then it’ll execute the code written under the except clause.

In short, when we define except clause in this way, we expect the same piece of code to throw different exceptions. Also, we want to take the same action in each case.

Please refer to the below example.


   You do your operations here;
except(Exception1[, Exception2[,...ExceptionN]]]):
   If there is any exception from the given exception list,
   then execute this block.
   If there is no exception then execute this block

How to handle Exceptions with Try-Finally?

What is Try-Finally Statement?

We can also enable Python exception handling with the help of try-finally statement.

With try block, we also have the option to define the “finally” block. This clause allows defining statements that we want to execute, no matters whether the try block has raised an exception or not.

This feature usually comes in the picture while releasing external resources.

Here is the coding snippet for help.

   You do your operations here;
   Due to any exception, this may be skipped.
   This would always be executed.


One critical point is that we can either define an “except” or a “finally” clause with every try block. You can’t club these together. Also, you shouldn’t use the “else” clause along with a “finally” clause.

Let’s take an example to get more clarity.

    fob = open('test', 'w')
    fob.write("It's my test file to verify try-finally in exception handling!!"
    print 'try block executed'
    print 'finally block executed'

If the exception doesn’t occur, then you’ll see the following output.

>>try block executed
>>finally block executed

Suppose we open the file in the READ mode and then try to perform a write operation on it. In such a situation, below code will help to handle the exception.

    fob = open('test', 'r')
        fob.write("It's my test file to verify try-finally in exception handling!!"
        print 'try block executed'
        print 'finally block executed to close the file'
except IOError:
    print "Error: can\'t find file or read data"

In this case, the interpreter will raise an exception, and the following output will get displayed.

>>finally block executed to close the file
>>Error: can\'t find file or read data

When some code causes an exception in a try block, the execution immediately passes to the “finally” block. After all the statements in the “finally” block gets executed, the exception resumes to the “except” block for execution. But there must present a next higher layer of the “try-except” statement.

Raise Exception with Arguments

What is Raise?

We can forcefully raise an exception using the raise keyword.

We can also optionally pass values to the exception and specify why it has occurred.

Raise Syntax

Here is the syntax for calling the “raise” method.

raise [Exception [, args [, traceback]]]


  • Under the “Exception” – specify its name.
  • The “args” is optional and represents the value of the exception argument.
  • The final argument, “traceback,” is also optional and if present, is the traceback object used for the exception.

Let’s take an example to clarify this.

Raise Example

>>> raise MemoryError
Traceback (most recent call last):
>>> raise MemoryError("This is an argument")
Traceback (most recent call last):
MemoryError: This is an argument
>>> try:
      a = int(input("Enter a positive integer value: "))
     if a <= 0:
            raise ValueError("This is not a positive number!!")
    except ValueError as ve:
Following Output is displayed if we enter a negative number:
Enter a positive integer: –5
This is not a positive number!!

Create Custom Exceptions in Python

What is a Custom Exception?

A custom exception is one which the programmer creates himself.

He does it by adding a new class. The trick here is to derive the custom exception class from the base exception class.

Most of the built-in exceptions do also have a corresponding class.

Create Exception Class in Python

>>> class UserDefinedError(Exception):
...     pass
>>> raise UserDefinedError
Traceback (most recent call last):
>>> raise UserDefinedError("An error occurred")
Traceback (most recent call last):
__main__.UserDefinedError: An error occurred

In the above code snippet, you can see that we have created a user-defined exception class, the “UserDefinedError.” It is using the base Exception class as the parent. Hence, the new user-defined exception class will raise exceptions as any other exception class does, i.e., by calling the “raise” statement with an optional error message.

Let’s take an example.


In this example, we will show how to raise an user-defined exception and catch errors in a program.

This program prompts the user to enter an alphabet again and again until he inputs the stored alphabet only.

For help, the program provides a hint to the user so that he can figure out the correct alphabet. Also, he can check whether his guess is higher or less than the stored alphabet.

#define Python user-defined exceptions
class Error(Exception):
   """Base class for other exceptions"""
class InputTooSmallError(Error):
   """Raised when the entered alpahbet is smaller than the actual one"""
class InputTooLargeError(Error):
   """Raised when the entered alpahbet is larger than the actual one"""

#our main program
#user guesses an alphabet until he/she gets it right
#you need to guess this alphabet
alphabet = 'm'
while True:
       apb =  raw_input("Enter an alphabet: ")
       if apb < alphabet:
           raise InputTooSmallError
       elif apb > alphabet:
           raise InputTooLargeError
   except InputTooSmallError:
       print("The entered alphabet is too small, try again!")
   except InputTooLargeError:
       print("The entered alphabet is too large, try again!")
print("Congratulations! You guessed it correctly.")

Let’s test this program by supplying different inputs.

Enter an alphabet: s
This value is too large, try again!
Enter an alphabet: a
This value is too small, try again!
Enter an alphabet: l
This value is too small, try again!
Enter an alphabet: p
This value is too large, try again!
Enter a number: m
Congratulations! You guessed it correctly.

Thus you can see that we have defined a base class called Error here in this program. It raises two exceptions (“InputTooSmallError” and “InputTooLargeError“) derived from the base class. It’s the standard way to define user-defined exceptions in Python programming.

Python Built-in Exceptions

ExceptionCause of Error
AirthmeticErrorFor errors in numeric calculation.
AssertionErrorIf the assert statement fails.
AttributeErrorWhen an attribute assignment or the reference fails.
EOFErrorIf there is no input or the file pointer is at EOF.
ExceptionIt is the base class for all exceptions.
EnvironmentErrorFor errors that occur outside the Python environment.
FloatingPointErrorIt occurs when the floating point operation fails.
GeneratorExitIf a generator’s <close()> method gets called.
ImportErrorIt occurs when the imported module is not available.
IOErrorIf an input/output operation fails.
IndexErrorWhen the index of a sequence is out of range.
KeyErrorIf the specified key is not available in the dictionary.
KeyboardInterruptWhen the user hits an interrupt key (Ctrl+c or delete).
MemoryErrorIf an operation runs out of memory.
NameErrorWhen a variable is not available in local or global scope.
NotImplementedErrorIf an abstract method isn’t available.
OSErrorWhen a system operation fails.
OverflowErrorIt occurs if the result of an arithmetic operation exceeds the range.
ReferenceErrorWhen a weak reference proxy accesses a garbage collected reference.
RuntimeErrorIf the generated error doesn’t fall under any category.
StandardErrorIt is a base class for all built-in exceptions except <StopIteration> and <SystemExit>.
StopIterationThe <next()> function has no further item to be returned.
SyntaxErrorFor errors in Python syntax.
IndentationErrorIt occurs if the indentation is not proper.
TabErrorFor inconsistent tabs and spaces.
SystemErrorWhen interpreter detects an internal error.
SystemExitThe <sys.exit()> function raises it.
TypeErrorWhen a function is using an object of the incorrect type.
UnboundLocalErrorIf the code using an unassigned reference gets executed.
UnicodeErrorFor a Unicode encoding or decoding error.
ValueErrorWhen a function receives invalid values.
ZeroDivisionErrorIf the second operand of division or modulo operation is zero.

Summary – Python Exception Handling Concepts

Most of the time, we aim to discover a topic that can help our readers in their work. That’s why we covered this tutorial on Python Exception Handling.

It would be great to hear from you if this post helped you in learning an essential concept of Python. Do let us know about your experience.

If you liked the post, then please don’t miss to share it with friends and on social media (Facebook/Twitter).

Teaching is the best asset that a person should share without any cost.

Keep Learning,