Python Exception Handling Beginner Tutorial

python exception handling tutorial for beginners

Like the literal meaning of Exception, in programming, exception handling is the technique for handling the exceptions which occur during a program execution. For example, when Python exception handling is the technique for handling exceptions in the python way.

Python Exception Handling

In this python exception handling beginner tutorial, you will learn how to handle exceptions in your python programs. We have explained it with working code blocks.

This is what you would be doing in exception handling.

1. Find all the possibilities of exceptions.

2. Identify the python exception category.

3. Handle the exceptions.

Recommended Resource: Python courses

The try except block

In python, an exception is handled in the try except block. It has the following format.


The operation you want to perform goes into the try block and other error handling operations go into the except block.

We will learn the python exception handling using a python program which creates a directory. Let’s take the following code as an example.

import os
import sys

directory = "demodir"

def createDir(dir):
        print("An Error Occured", sys.exc_info() )


The above code has a method named createDir with an dir argument. If execute the above code, a directory named demodir will be created in the current working directory.

If you execute the same program again, you will get the following output with error details.

[vagrant@pythondev python]$ python
('An Error Occured', (<type 'exceptions.OSError'>, OSError(17, 'File exists'), ))

So what happened

When you executed the code for the first time, the code in the try block got executed and it created a directory.

For the second time, it tried to execute the code in try block but a directory named demodir already exists. That exception was caught by the except block and it printed the error message specified in that block. Also, it printed the type of exception which occurred OSError

using the sys.exc_info()[0] function.

Now we know that the type of exception occurred was an OSError

. Now you can modify the except block as follows.

except OSError:
  print("Folder already Exist. Please delete it or try with a different name")

Now, if you execute the program, you will see the error message specified in the except block. Likewise, you can have many except blocks to handle different error categories. When you write programs, it is not sure that only one type of error would occur. So you need to find all the possible exception errors and declare it in the except block as shown below.

   # main operation

except OSError:
   # handles OSError exception

except (ArithmeticError, EnvironmentError):
   # handles differnt exceptions

   # handles exceptions which are not mentioned above

Defining Custom Exceptions

In some situations, you might want to register custom exceptions. Let’s say, you want to add a condition like, there should not be any special characters in the directory name. In this case, you can create and condition and raise an exception if the user tries to create a directory with special characters.

Take a look at the following example and try executing it.

import os
import sys

directory = "demodir_"
symbols = "~!@#$%^*()_-+={}[]:>;',</?*-+"
def createDir(dir):
        if any(char in symbols for char in directory):
            raise ValueError("The directory name contains special characters. Please use only alphabets")
    except ValueError as ve:
    except OSError:
        print("Folder already Exist. Plese delte it or try with a differnt name")

In the above example, we have renamed the directory with a special character. Also, the symbols variable contains a list of special characters. And we are checking for special characters in the directory name in the try block. Since our directory has a special character mentioned in the symbols variable, it will raise an exception and prints the exception using the except ValueError as ve block. Basically ve contains the error message raised in the try block.

The finally block

In certain cases, you might want to run a certain code block even if the program has an exception. In this case, you can use the finally block. It is used in conjunction with the try block.

Let’s take an example where you want to log every attempt for directory creation. In this case, you need a log the directory creation attempt even it raises an exception. Let’s take a look at the following try block.

        with open("directory.log", "a") as myfile:
            myfile.write("directory creation attempted at %s" % str(

Add import datetime at the top and add the above block after all exceptions. Also, create a directory.log file in the current working directory.

Now if you execute your program, you will see the logs with a timestamp appended to the directory.log file.


Hope you understood the python exception handling concepts and scenarios. If you liked this article, please share it using the social media buttons.


The new economy needs a new approach to education. Education is no longer a one-time investment at the beginning of one's career, it's a lifelong pursuit. We're building an educational experience that empowers our readers to thrive in this new world order.

Leave Comment