简体   繁体   English

错误发生时运行功能,无需尝试

[英]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. 我不想使用tryexcept因为我的代码很大,并且发生错误的可能性很大,所以我不能在任何地方使用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.

相关问题 尝试和除了返回错误,但是当没有运行时,没有错误发生? - Try and except returns error, however when run without, no error occurs? Pyhon:程序中出现错误时,运行函数的更好方法? - Pyhon: A better way to run a function when an error occurs in the program? 尽管安装了 tensorflow,当我尝试从 CMD 运行文件时,出现“ModuleNotFoundError: No module named 'tensorflow'”错误 - Inspite of installing tensorflow, `ModuleNotFoundError: No module named 'tensorflow'` error occurs when I try to run files from CMD 当我尝试使用函数参数作为列表索引时,出现错误“列表索引必须是整数或切片,而不是元组” - Error “list indices must be integers or slices, not tuple” occurs when I try to use function parametrs as list indices 发生错误时如何运行其他代码? - How to run other code when an error occurs? 当我尝试将列表传递给我的 class 属性时发生错误 - error occurs when I try to pass a list to my class attributes 当您尝试将数据类型分配给python中的输入时发生错误 - An error occurs when you try to assign a data type to a input in python 发生错误时更改变量而不终止程序 - Changing a variable when an error occurs without terminating the program 尝试在没有禁止权限的情况下禁止用户时发生错误 - Error occurs when trying to ban user without ban permission 发生错误时关闭文件而不保存 - Python - Close a file without saving when an error occurs - Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM