20 条回复  ·  2254 次点击
pollux 小成 2025-6-24 12:12:29
自己写一个装饰器做异常捕捉 ``` #!/opt/python3108/bin/python3.10 from functools import wraps def catch_specific_exceptions(func): @wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: print(f"捕获到异常: {e}") return None return wrapper @catch_specific_exceptions def specific_operation(x, y): return x / y @catch_specific_exceptions def read_file(file): f = open(file) data = json.load(f) f.close() specific_operation(10, 0) read_file("x.json") ``` 捕获到异常: division by zero 捕获到异常: [Errno 2] No such file or directory: 'x.json'
123
返回顶部