Handling Errors with try Statements

The preceding solution works, but as you’ll see later in the book, the most general way to handle errors in Python is to catch and recover from them completely using the Python try statement. We’ll explore this statement in depth in Part VII of this book, but as a preview, using a try here can lead to code that some would claim is simpler than the prior version:

while True:
    reply = input('Enter text:')
    if reply == 'stop': break
    try:
        num = int(reply)
    except:
        print('Bad!' * 8)
    else:
        print(int(reply) ** 2)
print('Bye')

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

This version works exactly like the previous one, but we’ve replaced the explicit error check with code that assumes the conversion will work and wraps it up in an exception handler for cases when it doesn’t. This try statement is composed of the word try, followed by the main block of code (the action we are trying to run), followed by an except part that gives the exception handler code and an else part to be run if no exception is raised in the try part. Python first runs the try part, then runs either the except part (if an exception occurs) or the else part (if no exception occurs).

In terms of statement nesting, because the words try, except, and else are all indented to the same level, they are all considered part of the same single try statement. Notice that the else part is associated with the try here, not the if. As we’ve seen, else can appear in if statements in Python, but it can also appear in try statements and loops—its indentation tells you what statement it is a part of. In this case, the try statement spans from the word try through the code indented under the word else, because the else is indented to the same level as try. The if statement in this code is a one-liner and ends after the break.

Again, we’ll come back to the try statement later in this book. For now, be aware that because try can be used to intercept any error, it reduces the amount of error-checking code you have to write, and it’s a very general approach to dealing with unusual cases. If we wanted to support input of floating-point numbers instead of just integers, for example, using try would be much easier than manual error testing—we could simply run a float call and catch its exceptions, instead of trying to analyze all possible floating-point syntax.