杰瑞科技汇

Python异常处理有哪些关键技巧?

Of course! Let's break down Python's Exception class in a clear and comprehensive way.

Python异常处理有哪些关键技巧?-图1
(图片来源网络,侵删)

What is Exception in Python?

In Python, an Exception is a special object that represents an error or an unexpected event that occurs during the execution of a program. When such an event happens, Python creates an Exception object and "raises" it. If the program doesn't have a mechanism to handle this raised exception, the program will terminate and display a "traceback," which is a report of what went wrong.

The Exception class is the base class for almost all built-in, non-system-exiting exceptions. Think of it as the "parent" class from which most other, more specific error types inherit.


The Hierarchy: BaseException vs. Exception

It's crucial to understand the difference between BaseException and Exception.

  • BaseException: This is the most fundamental base class for all exceptions, including system-exiting ones.

    Python异常处理有哪些关键技巧?-图2
    (图片来源网络,侵删)
    • SystemExit: Raised by sys.exit() to terminate the program.
    • KeyboardInterrupt: Raised when the user presses Ctrl+C.
    • GeneratorExit: Raised when a generator is closed.
    • And all other exceptions, including Exception.
  • Exception: This is the base class for all non-system-exiting exceptions. These are the errors you typically want to catch and handle in your application code (e.g., trying to divide by zero, accessing a non-existent key in a dictionary).

Why does this matter? Because when you write a try...except block, if you catch BaseException, you will also catch SystemExit and KeyboardInterrupt. This is usually a bad idea, as it can prevent your program from exiting normally or being stopped by the user.

Good Practice:

# GOOD: Catches errors you expect and can handle.
try:
    result = 10 / 0
except Exception as e:
    print(f"An error occurred: {e}")
# BAD: This will also catch Ctrl+C and sys.exit(), making it hard to stop the program.
try:
    # some code
except BaseException:
    print("Caught everything!")

How to Use Exception in Practice

There are two main ways you'll interact with Exception:

Python异常处理有哪些关键技巧?-图3
(图片来源网络,侵删)
  1. Catching Exceptions: Using a try...except block to handle errors gracefully.
  2. Raising Exceptions: Using the raise keyword to manually create and trigger an error.

Catching Exceptions

You catch exceptions to prevent your program from crashing and to handle the error in a controlled way.

Basic Syntax:

try:
    # Code that might raise an exception
    risky_code()
except SpecificException as e:
    # Code to run if SpecificException occurs
    # 'e' is the exception object
    handle_error(e)
except AnotherException as e:
    # Code to run if AnotherException occurs
    handle_another_error(e)
else:
    # Code to run ONLY if no exceptions occurred in the 'try' block
    print("Success!")
finally:
    # Code to run NO MATTER WHAT (whether an exception occurred or not)
    # Often used for cleanup (e.g., closing a file)
    print("Cleaning up...")

Example:

try:
    num_str = input("Enter a number to divide 100 by: ")
    result = 100 / int(num_str)
    print(f"The result is {result}")
except ValueError as e:
    # This block runs if int(num_str) fails (e.g., user enters "hello")
    print(f"Invalid input: {e}. Please enter a valid number.")
except ZeroDivisionError as e:
    # This block runs if the number is 0
    print(f"Cannot divide by zero: {e}")
except Exception as e:
    # A "catch-all" for any other unexpected errors
    print(f"An unexpected error occurred: {e}")
else:
    print("Calculation completed successfully.")
finally:
    print("This block always runs.")

Raising Exceptions

You can (and should) raise exceptions in your own code when something goes wrong that your function cannot handle. This makes your functions more robust and communicates errors clearly to whoever is using your code.

Syntax: raise Exception("Error message here")

Example: Let's create a function that checks if a user is old enough to vote.

def check_voting_age(age):
    """
    Checks if a person is old enough to vote.
    Raises a ValueError if the age is invalid.
    """
    if not isinstance(age, int) or age < 0:
        # We raise an exception to signal invalid input
        raise ValueError("Age must be a positive integer.")
    if age >= 18:
        print("You are eligible to vote.")
    else:
        print("You are not yet eligible to vote.")
# --- Using the function ---
try:
    check_voting_age(20)  # Valid case
    check_voting_age(-5)  # Invalid case, will raise ValueError
except ValueError as e:
    print(f"Error caught: {e}")
# Output:
# You are eligible to vote.
# Error caught: Age must be a positive integer.

Creating Custom Exceptions

For larger applications, it's a best practice to create your own custom exception classes that inherit from Exception. This makes your error handling more specific and meaningful.

How to do it: Simply create a new class that inherits from Exception.

Example:

# Define a custom exception
class InsufficientFundsError(Exception):
    """Custom exception for when an account has insufficient funds."""
    pass
class BankAccount:
    def __init__(self, balance):
        self.balance = balance
    def withdraw(self, amount):
        if amount > self.balance:
            # Raise our custom exception with a helpful message
            raise InsufficientFundsError(f"Cannot withdraw ${amount}. Your balance is only ${self.balance}.")
        self.balance -= amount
        print(f"Withdrew ${amount}. New balance: ${self.balance}.")
# --- Using the custom exception ---
account = BankAccount(100)
try:
    account.withdraw(50) # This will work
    account.withdraw(100) # This will raise our custom exception
except InsufficientFundsError as e:
    print(f"Transaction failed: {e}")
# Output:
# Withdrew $50. New balance: $50.
# Transaction failed: Cannot withdraw $100. Your balance is only $50.

Key Takeaways

  1. Exception is the Base: It's the parent class for most errors you'll want to handle in your application code.
  2. Catch Specific Exceptions: Always try to catch specific exceptions (like ValueError) instead of a generic Exception if you know what might go wrong. This makes your code more robust.
  3. Use try...except...else...finally: This structure gives you full control over error handling, success cases, and cleanup.
  4. Raise Exceptions for Errors: Use raise to signal that something has gone wrong in your function. It's better to fail fast and clearly.
  5. Create Custom Exceptions: For complex applications, create your own exception classes that inherit from Exception to make your error handling clean and expressive.
分享:
扫描分享到社交APP
上一篇
下一篇