【问题标题】:python2.7--TypeError: exceptions must be old-style classes or derived from BaseException, not str [duplicate]python2.7--TypeError:异常必须是旧式类或派生自BaseException,而不是str [重复]
【发布时间】:2016-05-03 12:34:22
【问题描述】:

python 2.7.10 中的以下代码

def inputnumber() :
    x = input('pick a number : ')
    if x == 17 :
        raise 'BadNumberError' , '17 is a bad number'
    return x

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

TypeError:异常必须是旧式类或派生自 BaseException,而不是 str

【问题讨论】:

    标签: python typeerror raise


    【解决方案1】:

    问题在于这不是 Python 中引发异常的方式。你raise 是一个派生自BaseException 的对象(通常它派生自built-in exception types 之一。因此,您的示例将被重新设计为:

    class BadNumberError(ValueError):
        pass
    
    def inputnumber():
        x = input('Pick a number: ')
        if x == 17:
            raise BadNumberError('17 is a bad number')
    
        return x
    

    结果是:

    [/home/.../Python/demos]$ python2.7 exception_demo.py 
    Pick a number: 17
    Traceback (most recent call last):
      File "exception_demo.py", line 11, in <module>
        print(inputnumber())
      File "exception_demo.py", line 7, in inputnumber
        raise BadNumberError('17 is a bad number')
    __main__.BadNumberError: 17 is a bad number
    [/home/.../Python/demos]$ python2.7 exception_demo.py 
    Pick a number: 18
    18
    

    需要注意的一点是,非常看到人们直接使用内置异常类型的实例是很常见的,像这样:

    def inputnumber():
        x = input('Pick a number: ')
        if x == 17:
            raise ValueError('17 is a bad number')
    
        return x
    

    它可能更方便,虽然我个人不喜欢它,因为它很难捕获由特定条件引起的异常。

    【讨论】:

      猜你喜欢
      • 2018-11-21
      • 2012-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-05
      • 2021-10-31
      相关资源
      最近更新 更多