Python Course Design Note 26 of 52

Exception Handling

Task Name: Exception Handling

Task Overview:

1. Know the common exceptions and the forms of exception catching

2. Be able to define custom exceptions

Discussion Topic:

When do you need to define a custom exception?

Check-in Requirements:

Complete the following exercises (the first can be answered verbally or in a post; for the second, upload a link to your code):

1. Describe in detail the common kinds of exceptions

2. Programming exercise: (all of the following is one question)

Define a custom Integer class

 -- The class has an input method; calling it always yields a valid number (non-numeric input is invalid, out-of-range input is invalid)

        ---- If the input is invalid because it is not a number, print the invalid message, and the user must enter again

         -- E.g. if 'abc' is entered, the invalid message is: invalid literal for int() with base 10: 'abc'

        ---- If the input is invalid because it is out of range, print the invalid message, and the user must enter again

         -- E.g. if '2147483648' is entered, the invalid message is: ErrorMsg: 2147483648 - out of range

        Hints:

        1) The method needs to catch and handle two exceptions (the built-in exception ValueError and the custom exception SlopOverError)

        2) The method is simpler to implement using recursion, but it is fine without recursion too

              -- The class has a verifySlopOver method that determines whether the number passed in is out of range (anything outside -2147483648 ~ 2147483647 is out of range)             ---- If the number is out of range, it actively raises the custom SlopOverError exception, passing in the number and the exception message   Custom exception class SlopOverError

 -- The class must override the \_\_init\_\_ method

        ---- It has two parameters, number and massage: number is the numeric value, massage is the exception message as a string

 -- The class must override the \_\_str\_\_ method

        ---- Format the exception information using the number and massage attributes