How to Handle More Specific to Less Specific Exceptions in Python - dummies

How to Handle More Specific to Less Specific Exceptions in Python

By John Paul Mueller

One strategy for handling exceptions in Python is to provide specific except clauses for all known exceptions and generic except clauses to handle unknown exceptions. Check out the exception hierarchy that Python uses. When viewing this chart, BaseException is the uppermost exception. Most exceptions are derived from Exception. When working through math errors, you can use the generic ArithmeticError or a more specific ZeroDivisionError exception.

Python evaluates except clauses in the order in which they appear in the source code file. The first clause is examined first, the second clause is examined second, and so on. The following steps help you examine an example that demonstrates the importance of using the correct exception order. In this case, you perform tasks that result in math errors.

  1. Open a Python File window.

    You see an editor in which you can type the example code.

  2. Type the following code into the window — pressing Enter after each line:

    try:
     Value1 = int(input("Type the first number: "))
     Value2 = int(input("Type the second number: "))
     Output = Value1 / Value2
    except ValueError:
     print("You must type a whole number!")
    except KeyboardInterrupt:
     print("You pressed Ctrl+C!")
    except ArithmeticError:
     print("An undefined math error occurred.")
    except ZeroDivisionError:
     print("Attempted to divide by zero!")
    else:
     print(Output)

    The code begins by obtaining two inputs: Value1 and Value2. The first two except clauses handle unexpected input. The second two except clauses handle math exceptions, such as dividing by zero. If everything goes well with the application, the else clause executes, which prints the result of the operation.

  3. Choose Run→Run Module.

    You see a Python Shell window open. The application asks you to type the first number.

  4. Type Hello and press Enter.

    As expected, Python displays the ValueError exception message. However, it always pays to check for potential problems.

  5. Choose Run→Run Module again.

    You see a Python Shell window open. The application asks you to type the first number.

  6. Type 8 and press Enter.

    The application asks you to enter the second number.

  7. Type 0 and press Enter.

    You see the error message for the ArithmeticError exception. What you should actually see is the ZeroDivisionError exception because it’s more specific than the ArithmeticError exception.

    image0.jpg

  8. Reverse the order of the two exceptions so that they look like this:

    except ZeroDivisionError:
     print("Attempted to divide by zero!")
    except ArithmeticError:
     print("An undefined math error occurred.")
  9. Perform Steps 5 through 7 again.

    This time, you see the ZeroDivisionError exception message because the exceptions appear in the correct order.

  10. Perform Steps 5 through 7 again, but type 2 for the second number instead of 0.

    This time, the application finally reports an output value of 4.0.

    image1.jpg

    Notice that the output is a floating-point value. Division results in a floating-point value unless you specify that you want an integer output by using the floor division operator (//).