本文介绍了Python:捕获特定异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想捕获特定的 ValueError ,而不仅仅是任何 ValueError .
我尝试过这样的事情:

I want to catch a specific ValueError, not just any ValueError.
I tried something like this:

try: maquina['WPF'] = macdat(ibus, id, 'WPF')
except: ValueError, 'For STRING = ’WPF’, this machine is not a wind machine.':
    pass

但是会引发 SyntaxError:无法分配给文字.
然后我尝试了:

But it raises a SyntaxError: can't assign to literal.
Then I tried:

try: maquina['WPF'] = macdat(ibus, id, 'WPF')
except ValueError, e:
    if e != 'For STRING = ’WPF’, this machine is not a wind machine.':
        raise ValueError, e

但是它提出了一个例外,即使它是我要避免的例外.

But it raises the exception, even if it is the one I want to avoid.

推荐答案

中,ValueError,e , e 除外,它是异常的实例,而不是字符串.因此,当您测试 e 是否不等于特定字符串时,该测试始终为False.试试:

in except ValueError,e, e is an instance of the exception, not a string. So when you test if e is not equal to a particular string, that test is always False. Try:

if str(e) != "..."

相反.

示例:

def catch(msg):
    try:
        raise ValueError(msg)
    except ValueError as e:  # as e syntax added in ~python2.5
        if str(e) != "foo":
            raise
        else:
            print("caught!")

catch("foo")
catch("bar")

通常,如果可以帮助您,您并不是真的希望依靠错误消息-有点太脆弱了.如果可以控制可调用的 macdat ,而不是在 macdat 中引发 ValueError ,则可以引发从继承的自定义异常ValueError :

Typically, you don't really want to rely on the error message if you can help it -- It's a little too fragile. If you have control over the callable macdat, instead of raising a ValueError in macdat, you could raise a custom exception which inherits from ValueError:

class MyValueError(ValueError): pass

然后,您只能捕获 MyValueError ,并让其他 ValueError 继续被其他事物捕获(或不捕获).简单的 ValueValue 除外仍然会捕获这种类型的异常,因此它在其他代码中的行为也应相同,这些代码也可能从此函数捕获ValueErrors.

Then you can only catch MyValueError and let other ValueErrors continue on their way to be caught by something else (or not). Simple except ValueError will still catch this type of exception as well so it should behave the same in other code which might also be catching ValueErrors from this function.

这篇关于Python:捕获特定异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 11:36