简体   繁体   English

尝试/排除某种类型的所有 Python 错误

[英]Try / Except all Python errors of a certain type

In my Python code, I'm using the PyQt5 module to display a GUI.在我的 Python 代码中,我使用 PyQt5 模块来显示 GUI。 Sometimes, I encounter a Runtime Error if I delete an element then attempt to use a function on the element's instance.有时,如果我删除一个元素然后尝试在该元素的实例上使用 function,我会遇到运行时错误。 This error is only displayed in the console, and it does not actually interfere with the GUI or terminate it.此错误仅显示在控制台中,实际上并不会干扰 GUI 或终止它。

Regardless, I would like to remove it (the Runtime Errors).无论如何,我想删除它(运行时错误)。 My first thought was to use a try/except block on the code, and except the Runtime Error that I was talking about.我的第一个想法是在代码上使用try/except块,除了我正在谈论的运行时错误。 The problem with this, is that if I encase my whole code with the try/except block, then if the error is caught, it will skip over to the end of my program and terminate:这样做的问题是,如果我用 try/except 块封装我的整个代码,那么如果错误被捕获,它将跳到我的程序末尾并终止:

try:
    # If any errors occur here...
    <code>
except RuntimeError:
    # The GUI will stop entirely, and the Python interpreter will skip to this line
    pass

Another solution to my problem is to encase any instance which could throw a RuntimeError with a try/catch block, like so:我的问题的另一个解决方案是使用try/catch块来封装任何可能引发 RuntimeError 的实例,如下所示:

try:
    # If any errors occur here...
    <code that may print an error>
except RuntimeError:
    # Python wont display the error
    pass

However given the mass amount of times I would need to do this in my code, I was wondering if there was a more efficient way of fixing this problem.但是考虑到我需要在我的代码中执行此操作的大量时间,我想知道是否有更有效的方法来解决此问题。

You can use customs decorators to to this (I don't know your python level but it's not the most beginner friendly thing).您可以为此使用海关装饰器(我不知道您的 python 级别,但这不是最适合初学者的东西)。 For example, this code here do not raise any error:例如,这里的代码不会引发任何错误:

from functools import wraps

def IgnoreError(f):
    @wraps(f)
    def wrapper():
        try:
            f()
        except ZeroDivisionError:
            pass
    return wrapper

@IgnoreError
def func1():
    x = 5/0

func1()

In your case, you will have to define this function:在您的情况下,您将必须定义此 function:

def IgnoreError(f):
    def wrapper(*args, **kwargs):
        try:
            f(*args, **kwargs)
        except RuntimeError:
            pass
    return wrapper

and then anytime you create a function that may raise the RuntimeError, just put the decorator @IgnoreError before your definition like this:然后任何时候你创建一个可能引发 RuntimeError 的 function,只需将装饰器@IgnoreError放在你的定义之前,如下所示:

@IgnoreError
def func():
   <your code here>

(if you want here's a video from TechWithTim explaining the decorators) (如果你想要这里是TechWithTim 解释装饰器的视频)

As per my comment, I would definitely go with the catch in the specific line calls that might throw the runtime error.根据我的评论,我肯定会 go 在可能引发运行时错误的特定行调用中捕获。 This avoids you accidentally suppressing another error you were not anticipating.这可以避免您意外抑制另一个您没有预料到的错误。

Depending on what the calls are that might give the runtime error, I would prefer a decorator pattern to hide the try-except logic.根据可能产生运行时错误的调用,我更喜欢装饰器模式来隐藏 try-except 逻辑。 Something like:就像是:

from functools import wraps


def catch_runtime_error(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except RuntimeError:
            pass  # or whatever handle you fancy

    return wrapper

which you would then use like:然后你会像这样使用:

@catch_runtime_error
def the_function_that_raises(...):
    # whatever the body is

the_function_that_raises(...)

Alternatively you can use it more directly in your code:或者,您可以在代码中更直接地使用它:

def the_function_that_raises(...):
    # whatever the body is

catch_runtime_error(the_function_that_raises)(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM