在Python中捕获特定的错误消息

2024-06-17 15:34:02 发布

您现在位置:Python中文网/ 问答频道 /正文

当我的某个依赖项抛出特定的ValueError时,我需要捕捉并以某种方式处理该错误,否则将重新引发该错误。 我没有发现任何最近的问题是以一种与python3兼容的方式来处理这个问题的,而且这种问题处理的唯一区别是返回的错误是字符串消息的情况。在

这篇文章可能是最接近的:Python: Catching specific exception

像这样的东西--catch specific HTTP error in python-不会起作用,因为我没有使用同样提供特定代码(如HTTP错误)的依赖项。在

我的尝试是:

try:
    spect, freq_bins, time_bins = spect_maker.make(syl_audio,
                                                   self.sampFreq)
except ValueError as err:
    if str(err) == 'window is longer than input signal':
        warnings.warn('Segment {0} in {1} with label {2} '
                      'not long enough for window function'
                      ' set with current spect_params.\n'
                      'spect will be set to nan.')
        spect, freq_bins, time_bins = (np.nan,
                                       np.nan,
                                       np.nan)
    else:
        raise

如果重要的话,依赖关系是不稳定的,我需要在谱图因特定原因而失败时进行捕捉(我获取谱图的片段比窗口函数短)。在

我意识到我的方法是脆弱的,因为它依赖于错误字符串不变,但是错误字符串是唯一区别于同一函数返回的其他ValueErrors的东西。所以我计划做一个单元测试来保护自己。在


Tags: 字符串inhttptime错误np方式nan
1条回答
网友
1楼 · 发布于 2024-06-17 15:34:02

好吧,根据其他人的评论,我猜应该是这样的:

# lower-level module
class CustomError(Exception):
    pass

# in method
Class Thing:
    def __init__(prop1):
        self.prop1 = prop1

    def method(self,element):
        try:
            dependency.function(element,self.prop1)
        except ValueError as err:
            if str(err) == 'specific ValueError':
                raise CustomError
            else:
                raise # re-raise ValueError because string not recognized

# back in higher-level module
thing = lowerlevelmodule.Thing(prop1)
for element in list_of_stuff:
    try:
        output = thing.method(element)
    except CustomError:
        output = None
        warnings.warn('set output to None for {} because CustomError'.
                       format(element))

相关问题 更多 >