Python Exception Handling

, , Comments Off on Python Exception Handling

This tutorial will give an introduction to what Python exceptions are, the most common types of exceptions, and how to handle raised exceptions with the try and except clauses.

What is a Python Exception?

A Python exception is a construct used to signal an important event, usually an error, that occurs when executing a program. An exception may cause the program to stop if it is not properly “caught” (i.e. handled correctly). If you think that your program might raise an exception when executed, you will find it useful to use try/except to handle them, which we’ll see in the next section.

Handling Exceptions

In the example below, we prompt user to enter a number, and after execution the program gives out the value of the given number squared. The program will work as long as you enter a number as your input.

while True:  
    x = int(raw_input("Please enter a number: "))
    print("%s squared is %s" % (x, x**2))

When you enter a string, or any other character that is not a number, like “one”, the program will raise a “Value Error” exception, as shown below:

$ python 
Please enter a number: 3  
3 squared is 9  
Please enter a number: 4  
4 squared is 16  
Please enter a number: five  
Traceback (most recent call last):  
  File "", line 4, in <module>
    x = int(raw_input("Please enter a number: "))
ValueError: invalid literal for int() with base 10: 'five'  

This is where handling exceptions comes in. You need to know how to properly handle exceptions, especially in production environments, because if they are not handled your program won’t know what to do and will crash.

Let’s see how we can handle the above error. This is done by surrounding the program that you think could raise an exception with a try keyword and matching it with a following except keyword to execute in case an exception is raised.

Let’s rewrite the same program, and this time take care of any exceptions that may arise.

while True:  
        x = int(raw_input("Please enter a number: "))
        print("%s squared is %s" % (x, x**2))
    except ValueError:
        print("Please enter a valid number!")

As you can see from the above program, the code inside the try statement is executed first. If no error occurs, the rest of the code is executed and the except statement is skipped.

Read full articler at Stackabuse