【python报错】TypeError:exceptions must be old-style classes or ...
1、问题描述
使用python2.7,代码中想要主动抛出一个异常,直接使用的raise 'xxxxxx',运行程序之后报错如下:
TypeError:exceptions must be old-style classes or derived from BaseException, not str.
使用python3,主动使用raise 'xxxxxx'抛出异常也是一样报错:TypeError:exceptions must derive from BaseException.
2、解决方法
根据报错描述,抛出的异常必须源于基异常,BaseException是所有异常类的基类,可以使用下列方法抛出异常:
raise Exception('xxxxxx')
如果确定抛出的异常类型,可以使用具体的异常类封装raise的信息:
raise ValueError('xxxxxx')
异常类型还有很多,继承关系大致如下:
BaseException:所有异常的公共基类.
Exception:所有非退出异常的通用基类,继承的BaseException.
其他异常类基本上都是继承的Exception.
# TODO 总结各种异常类,以图表+描述的形式画出。