Python中异常处理的最佳实践:十个示例

原创 叁歲伎倆 2025-03-05 02:57 16阅读 0赞

在 Python 中,异常处理是一种机制,用于检测和管理程序运行过程中的错误。以下是一些关于异常处理的优秀实践示例:

  1. 使用 try/except 块

    1. def divide_numbers(a, b):
    2. try:
    3. return a / b
    4. except ZeroDivisionError:
    5. print("Cannot divide by zero!")
    6. return None
    7. result = divide_numbers(10, 5)
    8. if result is not None:
    9. print(result)
  2. 明确异常类型

    1. def validate_email(email):
    2. try:
    3. emailaddress = email.lower()
    4. # 检查常见的无效邮箱格式
    5. if '@' not in emailaddress or '.' not in emailaddress:
    6. raise ValueError("Invalid email format.")
    7. return email
    8. except ValueError as ve:
    9. print(ve)
    10. return None
    11. email = "invalid_email@domain.com"
    12. validated_email = validate_email(email)
    13. if validated_email is not None:
    14. print(validated_email)
  3. 使用 finally 块清理资源

    1. def open_file(filename, mode):
    2. try:
    3. f = open(filename, mode))
    4. return f
    5. except FileNotFoundError:
    6. print(f"{filename} not found!"))
    7. return None
    8. finally:
    9. if 'f' in locals(): # check for 'f' in locals()
    10. f.close() # close the file
    11. filename = "example.txt"
    12. opened_file = open_file(filename, "r")
    13. if opened_file is not None:
    14. print(opened_file.read()))
  4. 避免过度处理异常

    1. def safe_division(a, b):
    2. try:
    3. result = a / b
    4. return result
    5. except ZeroDivisionError:
    6. # 返回一个有意义的值,如 -1
    7. return -1
    8. division_result = safe_division(10, 5)
    9. print(division_result) # 输出:2.0
  5. 利用 logging 追踪错误

    1. import logging
    2. def setup_logger(filename, level=logging.INFO):
    3. logger = logging.getLogger(__name__)
    4. logger.setLevel(level)
    5. handler = logging.FileHandler(filename)
    6. handler.setLevel(logging.DEBUG)
    7. formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    8. handler.setFormatter(formatter)
    9. logger.addHandler(handler)
    10. return logger
    11. filename = "error_log.txt"
    12. logger = setup_logger(filename, level=logging.ERROR)
    13. def some_function():
    14. # 模拟可能引发错误的代码
    15. nonexistent_attribute = some_object().nonexistent_attribute
    16. try:
    17. some_function()
    18. logger.info("Some function executed successfully.")
    19. with open(filename, "a")) as f:
    20. f.write("Execution success logged to file.\n")
    21. except Exception as e:
    22. # 记录错误日志
    23. logger.error(f"An error occurred during execution: {e}") )
    24. with open(filename, "a")) as f:
    25. f.write(f"{str(e)} - Error logging in file.\n") )
    26. finally:
    27. logger.removeHandler(handler) # 关闭日志处理器
  6. 避免全局异常处理

    1. class MyClass:
    2. def some_method(self):
    3. # 模拟可能会抛出异常的代码
    4. try:
    5. result = do_something()
    6. return result
    7. except SomeException as se:
    8. self.handle_exception(se)
    9. return None
    10. def handle_exception(self, exception):
    11. print(f"Handling error: {exception}")
    12. # 这里可以添加自定义错误处理逻辑
    13. my_instance = MyClass()
    14. result = my_instance.some_method()
    15. if result is not None:
    16. print(result)
  7. 使用局部异常处理

    1. def divide_numbers(a, b):
    2. try:
    3. return a / b
    4. except ZeroDivisionError:
    5. # 这里是捕获到错误后执行的代码
    6. print("Cannot divide by zero!")
    7. return None
    8. def some_function():
    9. a = 10
    10. b = 5
    11. result = divide_numbers(a, b)
    12. if result is not None:
    13. print(f"Result: {result}")
    14. try:
    15. some_function()
    16. except Exception as e:
    17. print(f"An error occurred: {e}")
  8. 使用 with 语句处理文件或资源

    1. def open_and_read_file(filename):
    2. try:
    3. with open(filename, "r") as f:
    4. content = f.read()
    5. return content
    6. except FileNotFoundError:
    7. print(f"{filename} not found!"))
    8. return None
    9. filename = "example.txt"
    10. file_content = open_and_read_file(filename)
    11. if file_content is not None:
    12. print(file_content)
  9. 对异常进行分级处理

    1. class CustomException(Exception):
    2. pass
    3. class NormalException(Exception):
    4. pass
    5. def some_function():
    6. try:
    7. # 正常业务逻辑代码
    8. pass
    9. except ZeroDivisionError as ze:
    10. # 处理特定的异常,这里为除零错误
    11. raise CustomException(f"Cannot divide by zero: {ze.__str__()}") from ze
    12. except NormalException as ne:
    13. # 可以对所有正常但需要处理的异常进行捕获并记录
    14. print(f"Caught normal exception: {ne.__str__()}}")
    15. finally:
    16. # 对所有类型的异常进行统一的清理操作,如关闭连接等
    17. pass
    18. try:
    19. some_function()
    20. except Exception as e:
    21. print(f"Encountered an error: {e}}")
  10. 结合日志和跟踪工具
    在处理复杂的系统或应用时,结合日志记录异常发生的时间、位置以及相关的上下文信息。同时,使用像 Sentry 这样的跟踪工具可以更好地帮助你定位问题的根源,并提供可能的解决方案。
  1. import logging
  2. sentry_integration = # 假设已集成 Sentry
  3. # 设置日志级别和输出路径
  4. logging.basicConfig(level=logging.ERROR, filename="app_errors.log", filemode="w")
  5. def handle_exception(exception, logger):
  6. try:
  7. # 在日志中记录异常信息
  8. logger.error(f"An error occurred: {exception.__str__()}"))
  9. # 将异常发送到 Sentry
  10. sentry_integration.capture exception
  11. # 再次尝试处理异常,这里假设重新抛出一个特定的异常
  12. raise ValueError("Failed to handle exception. Please check Sentry logs for more details.") from exception
  13. except Exception as e:
  14. # 如果在向上抛出异常的过程中又出现了新的异常,我们需要记录这个新出现的异常
  15. logger.error(f"An unexpected error occurred while handling the original exception: {e.__str__()}"))
  16. sentry_integration.capture exception
  17. # 在需要处理异常的地方调用 handle_exception 函数
  18. try:
  19. some_function() # 假设在 some_function() 中发生了错误
  20. except Exception as e:
  21. handle_exception(e, logging.getLogger(__name__)))) # 将捕获的异常传递给 handle_exception 函数处理

```

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

发表评论

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

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

相关阅读

    相关 Python异常处理最佳实践

    在Python中,异常处理是编程中的一个重要环节,它可以帮助我们更好地控制程序的流程,避免因为意外情况导致程序崩溃。以下是一些最佳实践: 1. **使用try/except块