【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、解決方法
根據(jù)報錯描述,拋出的異常必須源于基異常,BaseException是所有異常類的基類,可以使用下列方法拋出異常:
raise Exception('xxxxxx')
如果確定拋出的異常類型,可以使用具體的異常類封裝raise的信息:
raise ValueError('xxxxxx')
異常類型還有很多,繼承關(guān)系大致如下:
BaseException:所有異常的公共基類.
Exception:所有非退出異常的通用基類,繼承的BaseException.
其他異常類基本上都是繼承的Exception.
# TODO 總結(jié)各種異常類,以圖表+描述的形式畫出。