热线电话:13121318867

登录
2018-10-23 阅读量: 1066
python错误解析(五)

代码如下:

bad = 'bad'  

try:
raise bad
except bad:
print 'Got Bad!'

错误:

Traceback (most recent call last):  
File "D:\Learn\Python\Learn.py", line 4, in <module>
raise bad
TypeError: exceptions must be old-style classes or derived from BaseException, not str

【错误分析】因所用的Python版本2.7,比较高的版本,raise触发的异常,只能是自定义类异常,而不能是字符串。所以会报错,字符串改为自定义类,就可以了。

代码如下:

class Bad(Exception):  
pass

def raiseException():
raise Bad()

try:
raiseException()
except Bad:
print 'Got Bad!'
0.0000
5
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子