理解Python:十大异常处理案例

原创 我不是女神ヾ 2025-03-13 06:18 17阅读 0赞

在Python编程中,异常处理是一项重要的技能。它允许我们在遇到错误或异常情况时,不会程序直接中断,而是采取合适的处理策略。下面列举了十大常见的Python异常处理案例:

  1. 除以零(ZeroDivisionError)
    1. try:
    2. result = 1 / 0
    3. except ZeroDivisionError as e:
    4. print("Error: ", str(e))
  2. 文件不存在(FileNotFoundError)
    1. filename = "non_existent_file.txt"
    2. try:
    3. with open(filename, 'r') as file:
    4. content = file.read()
    5. except FileNotFoundError as e:
    6. print("Error: ", str(e)))
  3. 类型错误(TypeError)
    ```python
    def add_string_numbers(s1, s2):
    return int(s1) + float(s2)

try:
result = add_string_numbers(‘1’, ‘2.0’)
except TypeError as e:
print(“Error: “, str(e)))

  1. 4. **逻辑错误(Logic Error)**:
  2. ```python
  3. def calculate_average(lst):
  4. if not lst:
  5. return "List is empty"
  6. else:
  7. total = sum(lst)
  8. average = total / len(lst)
  9. return average
  10. try:
  11. result = calculate_average([1, 2, 3], [4, 5, 6]])
  12. except Exception as e:
  13. print("Error: ", str(e)))
  1. 资源不足(Resource Insufficient)
    1. def process_large_file(file_path):
    2. try:
    3. with open(file_path, 'r') as file:
    4. for line in file:
    5. # 这里处理大型文件,可能会消耗大量内存或CPU时间
    6. pass
    7. except Exception as e:
    8. print("Error processing large file: ", str(e)))
  2. 无限循环(Infinite Loop)
    ```python
    def infinite_loop():
    while True:
    1. print("This is an infinite loop!")

infinite_loop()

  1. 7. **异常传播(Exception Propagation)**:
  2. ```python
  3. try:
  4. a = 10 / 0
  5. except ZeroDivisionError as e:
  6. print(f"Error: {str(e)}}")
  1. 特定异常捕获(Specific Exception Catching)
    ```python
    def divide_numbers(a, b):
    try:
    1. result = a / b
    2. return result
    except ZeroDivisionError:
    1. print("Error: Division by zero is not allowed.")
    2. return None

number1 = 10
number2 = 0

result = divide_numbers(number1, number2)
if result is not None:
print(f”The division result is {result}).”)

  1. 9. **异常处理链(Exception Handling Chain)**:
  2. ```python
  3. def calculate_total(numbers):
  4. total = sum(numbers)
  5. if total < 0:
  6. raise ValueError("Total cannot be negative.")
  7. return total
  8. numbers = [1, 2, 3], [-4, -5, -6]]
  9. try:
  10. result = calculate_total(numbers)
  11. print(f"The total is {result}).")
  12. except ValueError as ve:
  13. print("Error: ", str(ve)))
  1. 异常处理与程序结构(Exception Handling and Program Structure)
    ```python
    class Calculator:
    def add(self, a, b):

    1. try:
    2. return a + b
    3. except Exception as e:
    4. print(f"Error in addition: {str(e)})}")

    def subtract(self, a, b):

    1. try:
    2. return a - b
    3. except Exception as e:
    4. print(f"Error in subtraction: {str(e)})}")

calculator = Calculator()
numbers1 = [2, 3]
numbers2 = [-4, -5]

try:
result_addition = calculator.add(numbers1, numbers2))
print(f”Result of addition: {result_addition}).”)

  1. result_subtraction = calculator.subtract(*numbers1, *numbers2))
  2. print(f"Result of subtraction: {result_subtraction}).")

except Exception as e:
print(“Error: “, str(e)))
```
以上案例展示了Python中如何通过try-except块来处理和控制异常。这样可以使程序更健壮,避免因为偶然的错误导致程序崩溃。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,17人围观)

还没有评论,来说两句吧...

相关阅读