gpt4 book ai didi

python - 异常处理: Differentiating between instances of the same error in Python

转载 作者:行者123 更新时间:2023-12-03 07:43:13 34 4
gpt4 key购买 nike

根据导致异常的原因的不同,建议分别处理相同类型异常的建议方法是什么?

假设有人希望以不同方式处理以下AttributeError的以下两个实例:

  • 'str' object has no attribute 'append'
  • 'float' object has no attribute '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

    我认为显而易见的答案是重构。我的问题专门针对那些效率低下或根本不可能的情况(如果有这样的情况)。

    最佳答案

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

    在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']

    由于我们不需要笨拙的东西,因此缩小了我们可以测试的范围,仅保留了 argswith_traceback。似乎最好的方法是使用 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')

    关于python - 异常处理: Differentiating between instances of the same error in Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47637955/

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