【问题标题】:TypeError:exceptions must be old-style classes or derived from BaseException, not strTypeError:exceptions 必须是旧式类或派生自 BaseException,而不是 str
【发布时间】:2012-07-14 21:11:41
【问题描述】:

以下是我的代码:

test = 'abc'
if True:
    raise test + 'def'

当我运行它时,它给了我TypeError

TypeError: exceptions must be old-style classes or derived from BaseException, not str

那么test应该是什么类型呢?

【问题讨论】:

    标签: python typeerror raise


    【解决方案1】:

    应该是个例外。

    你想做这样的事情:

    raise RuntimeError(test + 'def')
    

    在 Python 2.5 及更低版本中,您的代码可以工作,因为它允许引发字符串作为异常。这是一个非常糟糕的决定,因此在 2.6 中被删除。

    【讨论】:

    • 您能解释一下为什么将字符串作为异常引发如此糟糕吗?
    • @BioGeek 字符串异常的问题包括仅在 raiseexcept 中都使用文字时才起作用,不提供用于将附加信息附加到异常的 OO 机制,而不是允许捕获多种异常类型的类别。异常是在类之前添加到语言中的,一旦添加了异常类,字符串异常只保留用于向后兼容。它们的删除,就像任何(错误)功能删除一样,简化了语言。
    • 感谢您提及上次支持此功能的版本。这对我有帮助。
    【解决方案2】:

    你不能 raisestr。只有Exceptions 可以是raised。

    所以,你最好用那个字符串构造一个异常并引发它。例如,您可以这样做:

    test = 'abc'
    if True:
        raise Exception(test + 'def')
    

    test = 'abc'
    if True:
        raise ValueError(test + 'def')
    

    希望有帮助

    【讨论】:

    • 另外,你不能不加任何参数就加注。
    【解决方案3】:

    raise 的唯一参数表示要引发的异常。这必须是异常实例或异常类(派生自 Exception 的类)。

    试试这个:

    test = 'abc'
    if True:
        raise Exception(test + 'def')
    

    【讨论】:

      猜你喜欢
      • 2018-11-21
      • 2016-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-25
      • 2023-03-09
      • 1970-01-01
      相关资源
      最近更新 更多