How to Handle a Single Exception in Python
Some things you develop in Python have a terrible habit of spitting out exceptions when the user inputs unexpected values. Part of the solution is to provide range checking. However, range checking doesn’t overcome the problem of a user typing text such as Hello in place of an expected numeric value. Exception handling provides a more complex solution to the problem, as described in the following steps.
1Open a Python File window.
You see an editor in which you can type the example code.
2Type the following code into the window — pressing Enter after each line:
try: Value = int(input("Type a number between 1 and 10: ")) except ValueError: print("You must type a number between 1 and 10!") else: if (Value > 0) and (Value <= 10): print("You typed: ", Value) else: print("The value you typed is incorrect!")
The code within the try block has its exceptions handled. In this case, handling the exception means getting input from the user using the int(input()) calls. If an exception occurs outside this block, the code doesn’t handle it.
With reliability in mind, the temptation might be to enclose all the executable code in a try block so that every exception would be handled. However, you want to make your exception handling small and specific to make locating the problem easier.
The except block looks for a specific exception in this case: ValueError. When the user creates a ValueError exception by typing Hello instead of a numeric value, this particular exception block is executed. If the user were to generate some other exception, this except block wouldn’t handle it.
The else block contains all the code that is executed when the try block code is successful (doesn’t generate an exception). The remainder of the code is in this block because you don’t want to execute it unless the user does provide valid input. When the user provides a whole number as input, the code can then range check it to ensure that it’s correct.
3Choose Run→Run Module.
You see a Python Shell window open. The application asks you to type a number between 1 and 10.
5Perform Steps 3 and 4 again, but type 5.5 instead of Hello.
The application generates the same error message.
6Perform Steps 3 and 4 again, but type 22 instead of Hello.
The application outputs the expected range error message. Exception handling doesn’t weed out range errors. You must still check for them separately.
7Perform Steps 3 and 4 again, but type 7 instead of Hello.
This time, the application finally reports that you’ve provided a correct value of 7. Even though it seems like a lot of work to perform this level of checking, you can’t really be certain that your application is working correctly without it.