在Python中,错误处理主要通过异常处理机制来实现
使用try-except语句捕获异常:def find_function(value): try: # 可能引发异常的代码 result = 10 / value except ZeroDivisionError: print("Error: Division by zero") return None except Exception as e: print(f"Error: {e}") return None else: return result# 调用find_functionresult = find_function(0)if result is not None: print(f"Result: {result}")使用try-except-else-finally语句处理多种异常:def find_function(value): try: # 可能引发异常的代码 result = 10 / value except ZeroDivisionError: print("Error: Division by zero") return None except TypeError: print("Error: Invalid input type") return None else: return result finally: print("Function execution completed")# 调用find_functionresult = find_function("a")if result is not None: print(f"Result: {result}")使用自定义异常类处理特定错误:class CustomError(Exception): passdef find_function(value): if value == "error": raise CustomError("Custom error occurred") return 10 / valuetry: result = find_function("error")except CustomError as e: print(f"Error: {e}")使用assert语句进行调试:def find_function(value): assert value != 0, "Division by zero" return 10 / valuetry: result = find_function(0)except AssertionError as e: print(f"Error: {e}")请根据您的需求选择合适的错误处理策略。在实际编程中,建议使用try-except语句来捕获和处理异常,以确保程序的稳定性和健壮性。


