Python Exception Handling

(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

Exception handling enables you handle errors gracefully and do something meaningful about it. Like display a message to user if intended file not found. Python handles exception using try .. except ..  block.


As you can see in try block you need to write code that might throw an exception. When exception occurs code in the try block is skipped. If there exist a matching exception type in except  clause then it’s handler is executed.

Let’s take an example:


The above code work as follows:

1. First statement between try  and except  block are executed.
2. If no exception occurs then code under except  clause will be skipped.
3. If file don’t exists then exception will be raised and the rest of the code in the try  block will be skipped
4. When exceptions occurs, if the exception type matches exception name after except  keyword, then the code in that except  clause is executed.

Note: The above code is only capable of handling IOError exception. To handle other kind of exception you need to add more except  clause.

A try  statement can have more than once except  clause, It can also have optional else  and/or finally  statement.

except  clause is similar to elif . When exception occurs, it is checked to match the exception type in except  clause. If match is found then handler for the matching case is executed. Also note that in last except  clause ExceptionType  is omitted. If exception does not match any exception type before the last except  clause, then the handler for last except  clause is executed.

Note:  Statements under the else  clause run only when no exception is raised.

Note: Statements in finally  block will run every time no matter exception occurs or not.

Now let’s take an example.


Note: The eval()  function lets a python program run python code within itself, eval()  expects a string argument.

To learn more about eval()  see the link

Raising exceptions

To raise your exceptions from your own methods you need to use raise  keyword like this

Let’s take an example

Run the program and enter positive integer.

Expected Output:

Again run the program and enter a negative number.

Expected Output:

Using Exception objects

Now you know how to handle exception, in this section we will learn how to access exception object in exception handler code. You can use the following code to assign exception object to a variable.

As you can see you can store exception object in variable ex . Now you can use this object in exception handler code

Run the program and enter a number.

Expected Output:

Again run the program and enter a string .

Expected Output:

Creating custom exception class

You can create a custom exception class by Extending BaseException  class or subclass of BaseException .

python exception classes

As you can see from most of the exception classes in python extends from the BaseException  class. You can derive you own exception class from BaseException  class or from sublcass of BaseException  like RuntimeError .

Create a new file called  and write the following code.

Above code creates a new exception class named NegativeAgeException , which consists of only constructor which call parent class constructor using super().__init__()  and sets the age .

Using custom exception class

In the next post we will learn about Python Modules.

Other Tutorials (Sponsors)

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

4 thoughts on “Python Exception Handling


    Firstly, this blog is useful, simple and clear.
    For the last part (Creating custom exception class) the hierarchy for built-in exceptions is:

    +-- SystemExit
    +-- KeyboardInterrupt
    +-- GeneratorExit
    +-- Exception
    +-- StopIteration
    +-- StopAsyncIteration
    +-- ArithmeticError
    | +-- FloatingPointError
    | +-- OverflowError
    | +-- ZeroDivisionError
    +-- AssertionError
    +-- AttributeError
    +-- BufferError
    +-- EOFError
    +-- ImportError
    +-- LookupError
    | +-- IndexError
    | +-- KeyError
    +-- MemoryError
    +-- NameError
    | +-- UnboundLocalError
    +-- OSError
    | +-- BlockingIOError
    | +-- ChildProcessError
    | +-- ConnectionError
    | | +-- BrokenPipeError
    | | +-- ConnectionAbortedError
    | | +-- ConnectionRefusedError
    | | +-- ConnectionResetError
    | +-- FileExistsError
    | +-- FileNotFoundError
    | +-- InterruptedError
    | +-- IsADirectoryError
    | +-- NotADirectoryError
    | +-- PermissionError
    | +-- ProcessLookupError
    | +-- TimeoutError
    +-- ReferenceError
    +-- RuntimeError
    | +-- NotImplementedError
    | +-- RecursionError
    +-- SyntaxError
    | +-- IndentationError
    | +-- TabError
    +-- SystemError
    +-- TypeError
    +-- ValueError
    | +-- UnicodeError
    | +-- UnicodeDecodeError
    | +-- UnicodeEncodeError
    | +-- UnicodeTranslateError
    +-- Warning
    +-- DeprecationWarning
    +-- PendingDeprecationWarning
    +-- RuntimeWarning
    +-- SyntaxWarning
    +-- UserWarning
    +-- FutureWarning
    +-- ImportWarning
    +-- UnicodeWarning
    +-- BytesWarning
    +-- ResourceWarning

  2. Yi Cui

    thank you so much for this tutorial. I have been following from the beginning and have really enjoyed your clear explaination, great exapmles and the clean layout of your site. I ran the example exactly as it is in the “Raising exceptions” section, but no matter what my input is, only the ValueError is thrown. It seems that the last except “something is wrong” is never executed. For example, even if I put in a letter instead of a number, I still got the ValueError. do you know why it is happening?

  3. Pavel

    First of all, thank you for the Tutorial. It is very helpful and useful.
    I would change the last code for the custom exception class like this:

    def enterage(age):
    if age < 0:
    raise NegativeAgeException(age)


    num = int(input(“Enter your age: “))
    except NegativeAgeException as ex:
    print(“Only positive integers are allowed, you’ve entered: “, ex.age)
    print(“something is wrong”)

    So we put user’s input as a custom exception var ‘age’. Then we can read it once exception occurs. I guess this is what the custom exception was designed to do, but in the post it just was missing.

    Expected output:
    Enter your age: -10
    Only positive integers are allowed, you’ve entered: -10


Leave a Reply

Your email address will not be published. Required fields are marked *