自己写一个装饰器做异常捕捉
```
#!/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_exceptionsdef specific_operation(x, y):
return x / y
@
catch_specific_exceptionsdef 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'