Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
异常处理:区分Python中相同错误的实例_Python_Python 3.x_Exception_Error Handling_Exception Handling - Fatal编程技术网

异常处理:区分Python中相同错误的实例

异常处理:区分Python中相同错误的实例,python,python-3.x,exception,error-handling,exception-handling,Python,Python 3.x,Exception,Error Handling,Exception Handling,根据导致异常的原因的不同,建议采用何种方式分别处理相同类型的异常 假设我们希望以不同方式处理以下两个AttributeError实例: “str”对象没有属性“append” “float”对象没有属性“append” 同时,我们不希望处理其他属性错误 是否有适用于所有异常类型的通用答案?我可以使用异常对象上的某些方法或函数来询问异常对象的详细信息吗 Try: blah Except AttributeError as exc: if exc.baz('foo') is ba

根据导致异常的原因的不同,建议采用何种方式分别处理相同类型的异常

假设我们希望以不同方式处理以下两个
AttributeError
实例:

  • “str”对象没有属性“append”
  • “float”对象没有属性“append”
同时,我们不希望处理其他属性错误

是否有适用于所有异常类型的通用答案?我可以使用异常对象上的某些方法或函数来询问异常对象的详细信息吗

Try:
    blah
Except AttributeError as exc:
    if exc.baz('foo') is bar:
         handle 'str' object has no attribute 'append'
    elif plugh(exc):
         handle 'float' object has no attribute 'append'
    else:
         raise exc

我认为显而易见的答案是重构。我的问题特别涉及效率低下或根本不可能做到的情况(如果有任何此类情况的话)

您可以通过使用查看对象具有哪些方法和属性

在Python 3.6中,来自:

a = 'hello'
try:
    a.append(2)
except AttributeError as e:
    print(dir(e))
你会得到:

['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', 'args', 'with_traceback']
这就缩小了我们可以测试的范围,因为我们不需要dunder,只剩下
args
具有回溯功能。因此,您最好使用
args
返回元组中的字符串:

a = 'hello'
try:
    a.append(2)
except AttributeError as e:
    if 'str' in e.args[0]:
        print('Need to handle string')
    elif 'float' in e.args[0]:
        print('Need to handle float')

这就是我害怕的。我之前尝试过使用可用属性。我知道不鼓励使用
.args
中的字符串,因为它依赖于版本,将来可能会更改。也许有一个天真的问题@roganjosh:为什么不能手动调用dunder方法?另外,我很快会接受你的回答,但我想再等一会儿,以防有人想出其他的办法。@lusubrator如果你愿意,如果你将异常子类化,dunder方法真的可以重写。我自己开始研究这个问题,但后来意识到我试图通过将
if
/
elif
打包到自定义异常中来创建一个自我处理异常,这似乎是荒谬的(更不用说我找不到访问
args
字符串的方法了)。尝试打印(例如,原因)
。不用担心等待,我发现这个问题很有趣,所以我也用它来学习:)@lusubrator,如果你愿意,你可以手动调用dunder方法。在我的最后一条评论中,我的意思是
打印(e.\uuu cause\uuu())
,但我现在无法编辑它。例如,在REPL中,您可以执行
a='hello'
然后执行
a.\uu str\uuu()
,这类似于调用
print(a)