如何区分ValueError的情况

blu*_*ote 10 python error-handling

由于返回了太多的python操作ValueError,我们如何区分它们?

示例:我希望一个iterable具有单个元素,并且我想获取它

  • a, = [1, 2]:ValueError:太多值无法解压
  • a, = []:ValueError:值太少而无法解压

我如何区分这两种情况?例如

try:
    a, = lst
except ValueError as e:
    if e.too_many_values:
        do_this()
    else:
        do_that()
Run Code Online (Sandbox Code Playgroud)

I realise that in this particular case I could find a work-around using length/indexing, but the point is similar cases come up often, and I want to know if there's a general approach. I also realise I could check the error message for if 'too few' in message but it seems a bit crude.

use*_*432 0

这并不是真正的答案,因为它仅适用于您对如何引发异常有一定控制的情况。由于异常只是对象,因此您可以将其他对象/标志附加到它们上。并不是说这是一件伟大的事情或做这件事的好方法:

from enum import Enum

class ValueErrorType(Enum):
    HelloType = 0,
    FooType = 1


def some_func(string):
    if "Hello" in string:
        error = ValueError("\"Hello\" is not allowed in my strings!!!!")
        error.error_type = ValueErrorType.HelloType
        raise error
    elif "Foo" in string:
        error = ValueError("\"Foo\" is also not allowed!!!!!!")
        error.error_type = ValueErrorType.FooType
        raise error

try:
    some_func("Hello World!")
except ValueError as error:
    error_type_map = {
        ValueErrorType.HelloType: lambda: print("It was a HelloType"),
        ValueErrorType.FooType: lambda: print("It was a FooType")
    }
    error_type_map[error.error_type]()
Run Code Online (Sandbox Code Playgroud)

我很想知道是否有某种方法可以实现这一目标,除非您无法控制它们的饲养方式。