Python Exception Handling

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.

Syntax:

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 http://stackoverflow.com/questions/9383740/what-does-pythons-eval-do

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 NegativeAgeException.py  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

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!

Leave a Reply

3 Comments on "Python Exception Handling"

Notify of
avatar

Sort by:   newest | oldest | most voted
Yi Cui
Guest
Yi Cui
8 months 3 days ago

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?

ILYAS KERBAL
Guest
ILYAS KERBAL
11 months 29 days ago
Firstly, this blog is useful, simple and clear. For the last part (Creating custom exception class) the hierarchy for built-in exceptions is: BaseException +-- 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 | +--… Read more »
wpDiscuz