Basic exception handling
To handle exceptions, you must tell Python that you want to do so
and then provide code to perform the handling tasks. You have a number of ways
in which you can perform this task. The following sections start with the
simplest method first and then move on to more complex methods that offer added
flexibility.
Handling a single exception
Some examples 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 over-come 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.
Open a Python File window.
You see an editor in which you can type the example code.
Type 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.
Choose Run➪Run Module.
You see a Python Shell window open. The application asks you to
type a number between 1 and 10.
Type Hello and press Enter.
The application displays an error message.
Typing the wrong input type generates an error instead of an
exception.
Perform Steps 3 and 4
again, but type 5.5 instead of Hello.
The application generates the same error message,.
Perform 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.
Exception handling doesn’t ensure that the value is in the correct
range.
Perform 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.
Perform Steps 3 and 4
again, but press Ctrl+C, Cmd+C, or the alterna-tive for your platform instead of
typing anything.
The application generates a KeyboardInterrupt exception. Because
this exception isn’t handled, it’s still a problem for the user. You see
several techniques for fixing this problem later in the Post.
Using the except clause without an exception
You can create an exception handling block in Python that’s
generic because it doesn’t look for a specific exception. In most cases, you
want to provide a specific exception when performing exception handling for
these reasons:
To avoid hiding an
exception you didn’t consider when designing the application
To ensure that others know
precisely which exceptions your application will handle
To handle the exceptions
correctly using specific code for that exception
However, sometimes you may need a generic exception-handling
capability, such as when you’re working with third-party libraries or
interacting with an external service. The following steps demonstrate how to
use an except clause without a specific exception attached to it.
Open a Python File window.
You see an editor in which you can type the example code.
Type the following code
into the window — pressing Enter after each line:
try:
Value = int(input("Type a number between 1 and 10: "))
except:
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 only difference between this example and the previous example
is that the except clause doesn’t have the ValueError exception specifi-cally
associated with it. The result is that this except clause will also catch any
other exception that occurs.
Choose Run➪Run Module.
Type Hello and press Enter.
The application displays an error message.
Perform Steps 3 and 4
again, but type 5.5 instead of Hello.
The application generates the same error message.
Perform 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.
Perform 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.
Perform Steps 3 and 4
again, but press Ctrl+C, Cmd+C, or the alternative for your platform instead of
typing anything.
You see the error message that’s usually associated with input
error. The error message is incorrect, which might con-fuse users. However, the
plus side is that the application didn’t crash, which means that you won’t lose
any data and the application can recover. Using generic exception handling does
have some advantages, but you must use it carefully.
0 comments:
Post a Comment