gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:58:29 26 4
gpt4 key购买 nike

我需要捕获我的一个依赖项何时引发特定的ValueError并以某种方式处理该错误,否则就重新引发该错误。
我没有发现任何最近的问题以符合Python 3的方式处理此问题,并且该问题仅能区分返回的错误是字符串消息。

这篇文章可能是最近的: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

如果这很重要,则依赖关系是科学的,当光谱图由于特定原因而失败时,我需要抓紧时间(我所拍摄的光谱图的段比窗口函数短)。

我意识到我的方法是脆弱的,因为它取决于错误字符串未更改,但是错误字符串是唯一将其与同一函数返回的其他ValueError区别的东西。因此,我计划进行单元测试以防万一。

最佳答案

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

# 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))

关于python - 在Python中捕获特定的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44910279/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com