杰瑞科技汇

Python中try-except如何高效捕获异常?

Of course! Let's break down Python's try...except block in a clear and comprehensive way.

Python中try-except如何高效捕获异常?-图1
(图片来源网络,侵删)

What is a try...except block?

In programming, an exception is an error that occurs during the execution of a program. If an exception is not handled, the program will crash. A try...except block is a fundamental construct in Python for error handling. It allows you to "try" a block of code that might raise an exception and then "catch" or "handle" that exception gracefully, preventing your program from crashing.

The basic idea is: Try to do something, and if it fails, do something else instead of crashing.


The Basic Syntax

The simplest form of the try...except block looks like this:

try:
    # Code that might raise an exception
    risky_operation()
except SomeError:
    # Code to run if SomeError occurs
    handle_the_error()

A Simple Example: Division by Zero

Let's start with the classic example of dividing by zero. This operation raises a ZeroDivisionError.

Python中try-except如何高效捕获异常?-图2
(图片来源网络,侵删)
# --- WITHOUT try...except ---
# This code will CRASH the program
# numerator = 10
# denominator = 0
# result = numerator / denominator
# print(f"The result is {result}") # This line will never be reached
# --- WITH try...except ---
# This code will run gracefully
numerator = 10
denominator = 0
try:
    # This code is "risky" because denominator could be 0
    result = numerator / denominator
    print(f"The result is {result}") # This line is skipped if an error occurs
except ZeroDivisionError:
    # This code only runs if a ZeroDivisionError happens in the 'try' block
    print("Error: You cannot divide by zero!")
print("The program continues to run after the error has been handled.")

Output:

Error: You cannot divide by zero!
The program continues to run after the error has been handled.

Notice how the program didn't crash. It printed a helpful error message and continued executing.


Key Components of try...except

The try Block

This is where you place the code that you suspect might cause an error. Python will "try" to execute this code line by line.

The except Block

This block contains the code that will be executed only if an exception of the specified type occurs in the try block.

Python中try-except如何高效捕获异常?-图3
(图片来源网络,侵删)
  • Catching a specific error: It's best practice to catch specific exceptions.

    except FileNotFoundError:
        print("The file you were looking for was not found.")
    except ValueError:
        print("That was not a valid number.")
  • Catching any error (Use with caution!): You can catch all exceptions by just using except:. However, this is generally discouraged because it can hide bugs (errors you didn't anticipate) and make your code harder to debug.

    except: # This will catch ALL exceptions
        print("An unexpected error occurred.")

The as keyword (Accessing the Exception Object)

When an exception occurs, it often contains useful information about the error. You can capture this exception object using the as keyword.

try:
    # Let's try to open a file that doesn't exist
    with open("non_existent_file.txt", "r") as f:
        content = f.read()
except FileNotFoundError as e:
    # 'e' now holds the exception object
    print(f"An error occurred: {e}")
    print(f"The error type is: {type(e)}")

Output:

An error occurred: [Errno 2] No such file or directory: 'non_existent_file.txt'
The error type is: <class 'FileNotFoundError'>

Advanced try...except Features

The finally Block

The finally block is an optional addition that executes no matter what. It runs whether an exception occurred or not, and whether it was handled or not. This is perfect for cleanup actions, like closing a file or a network connection.

try:
    f = open("my_file.txt", "w")
    f.write("Hello, world!")
    # If we uncomment the next line, the IOError will be caught,
    # but the 'finally' block will still run.
    # f.read() # This will raise an IOError because the file is opened in 'write' mode.
except IOError as e:
    print(f"An I/O error occurred: {e}")
finally:
    # This code ALWAYS runs
    print("Closing the file.")
    f.close() # Important for releasing resources
print("Program finished.")

Output (regardless of an error):

Closing the file.
Program finished.

Multiple except Blocks

You can have multiple except blocks to handle different types of errors that might occur in the same try block. Python will execute the first except block that matches the raised exception.

try:
    value = input("Please enter a number: ")
    result = 10 / int(value)
except ValueError:
    print("Invalid input. You must enter a number.")
except ZeroDivisionError:
    print("You cannot divide by zero.")
except Exception as e:
    print(f"An unexpected error happened: {e}")
else:
    print(f"The result is {result}")

In this example:

  • If the user enters "hello", a ValueError is caught.
  • If the user enters "0", a ZeroDivisionError is caught.
  • Any other unexpected error would be caught by the generic Exception block.

The else Block with try...except

You can use an else block with a try...except statement. The code in the else block will only run if the try block completes successfully without raising any exceptions. This is useful for separating the "risky" code from the code that should only run on success.

try:
    num_str = input("Enter a positive number: ")
    num = int(num_str)
except ValueError:
    print("That's not a valid integer!")
else:
    # This code only runs if the 'try' block was successful
    if num > 0:
        print(f"The square of {num} is {num * num}.")
    else:
        print("The number is not positive.")

Best Practices

  1. Be Specific: Always try to catch the most specific exception you can. Don't use a bare except: unless you have a very good reason. This prevents you from catching and ignoring errors you didn't see coming.

    # Good
    try:
        # ... code ...
    except ValueError:
        # ...
    # Bad
    try:
        # ... code ...
    except: # Catches EVERYTHING, including SystemExit and KeyboardInterrupt
        # ...
  2. Use finally for Cleanup: Use the finally block for any actions that must be performed, such as closing files, releasing locks, or closing database connections.

  3. Don't Use try...except for Flow Control: try...except is for handling exceptional events, not for normal program flow. For example, don't use it to check if a key exists in a dictionary; use if key in my_dict: instead.

    # Bad Practice: Using try/except for normal logic
    my_dict = {'a': 1, 'b': 2}
    try:
        value = my_dict['c']
    except KeyError:
        value = 0
    # Good Practice: Using standard logic
    my_dict = {'a': 1, 'b': 2}
    value = my_dict.get('c', 0) # .get() is the right tool for this job

Summary Table

Keyword Purpose When it Executes
try Defines a block of code to test for errors. Always.
except Defines a block of code to handle a specific error. Only if the corresponding error occurs in the try block.
finally Defines a block of code to run, regardless of whether an error occurred. Always.
raise (Not part of try/except but related) Forces an exception to occur. Manually, when called.
分享:
扫描分享到社交APP
上一篇
下一篇