What is exception handling?

Exception handling is a mechanism to handle the exceptions that are generated by runtime errors.

Example

Consider the following program:

num1 = input("Input number 1: ")
num2 = input("Input number 2: ")
num1 = int(num1)
num2 = int(num2)
num3 = num1 + num2
print("number1 + number2 =", num3)

If we were to run this program using the values 1 and 2 as input.  The output from the program would be:

Input number 1: 1
Input number 2: 2
number1 + number2 = 3

However, if we were to run this program using the values 1 and tree as input. The output from the program would be:

Input number 1: 1
Input number 2: tree
Traceback (most recent call last):
  File "exception_ex_1.py", line 4, in <module>
    num2 = int(num2)
ValueError: invalid literal for int() with base 10: 'tree'

Notice how this execution generated an exception on line 4.

Line 4 of the program contains the following line of code:

num2 = int(num2)

We are attempting to cast the value in the variable num2 to an int.

However, we executed the program we inputted the value tree which was stored in num2.  We cannot cast this value to an int, hence the ValueError exception.

ValueError: invalid literal for int() with base 10: 'tree'

We can use exception handling to catch this exception, without generating a runtime error and crashing the program.

Exception handling in Python

We use a TRY...CATCH structure to accomplish this.

How this works

  • The try phase - try to execute a block of code
  • if no exception is generated
    • continue with the program
  • The catch phase - if an exception is generated
    • catch the exception (so that a runtime error does not occur)
    • do something (usually this will be something to remedy the error)
    • continue with the program

The program using exception handling

num1 = input("Input number 1: ")
num2 = input("Input number 2: ")
while True:
    try:
        num1 = int(num1)
        break
    except:
        print("Whatever you inputted cannot be casted to an integer")
        num2 = input("Please input number 1 again: ")
while True:
    try:
        num2 = int(num2)
        break
    except:
        print("Whatever you inputted cannot be casted to an integer")
        num2 = input("Please input number 2 again: ")
num3 = num1 + num2
print("number1 + number2 =", num3)

This time if we were to run this program using the values 1 and tree as input. The output from the program would be:

Input number 1: 1
Input number 2: tree
Whatever you inputted cannot be casted to an integer
Please input number 2 again: 2
number1 + number2 = 3