[英]Run function when error occurs without try
I am trying to run a function whenever an error occurs. 每当出现错误时,我都试图运行一个函数。 I don't want to use
try
or except
because my code is very large and there are so much chances of an error to occur , so I can't use try
.. everywhere. 我不想使用
try
或except
因为我的代码很大,并且发生错误的可能性很大,所以我不能在任何地方使用try
..。 This is what I am expecting: 这是我所期望的:
>>> if ValueError: #don't works , just assuming.
print("Hey! You are done.")
>>> int("abc")
Hey! You are done.
>>> int("1b")
Hey! You are done.
>>>
Is there any way to do this? 有什么办法吗?
If your code is a whole block, I recommend splitting it into functions. 如果您的代码是一个完整的块,建议将其拆分为多个函数。 From here, you can wrap each function in a decorator that takes an error and a function to be run on error:
在这里,您可以将每个函数包装在一个装饰器中,该装饰器会出现错误,并在错误时运行一个函数:
def handle_error(error, error_func):
def decorator(func):
def wrapper(*args, **kwargs):
r = None
try:
r = func(*args, **kwargs)
except error as e:
r = error_func()
finally:
return r
return wrapper
return decorator
Then use on functions like so: 然后使用像这样的函数:
def bad_value():
print('bad value given!')
@handle_error(ValueError, bad_value)
def multiply(a, b):
return a * b
Of course, you can be more 'broad', and catch all exceptions... 当然,您可以更加“广泛”,并抓住所有例外情况...
@handle_error(Exception, error_func)
def func():
# ...
A ValueError is triggered by a particular piece of code, and will raise itself immediately after the offending statement. ValueError由特定的代码段触发,并将在违规语句之后立即引发自身。
int("abc")
will raise a ValueError on its own, and the program execution will stop, before it reaches any if ValueError
statement. int("abc")
将自行引发ValueError,并且在到达任何if ValueError
语句之前,程序执行将停止。
You need a try
/ except
block to allow python to catch the error and continue executing. 您需要一个
try
/ except
块,以允许python捕获错误并继续执行。 I can't see any way to achieve what you want without one. 没有一个人,我看不到任何方法来实现您想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.