阅读量:0
在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_function result = 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_function result = find_function("a") if result is not None: print(f"Result: {result}")
- 使用自定义异常类处理特定错误:
class CustomError(Exception): pass def find_function(value): if value == "error": raise CustomError("Custom error occurred") return 10 / value try: 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 / value try: result = find_function(0) except AssertionError as e: print(f"Error: {e}")
请根据您的需求选择合适的错误处理策略。在实际编程中,建议使用try-except
语句来捕获和处理异常,以确保程序的稳定性和健壮性。