Chinaunix首页 | 论坛 | 博客
  • 博客访问: 486922
  • 博文数量: 173
  • 博客积分: 4112
  • 博客等级: 上校
  • 技术积分: 1577
  • 用 户 组: 普通用户
  • 注册时间: 2010-02-26 10:12
文章分类

全部博文(173)

文章存档

2012年(1)

2010年(172)

我的朋友

分类: Python/Ruby

2010-08-08 21:26:40

Python 的异常处理机制和 C# 类似。

 

Code
>>>>>> try:
raise Exception("a", "b")
except Exception,e:
print e
finally:
print "final"


(
'a', 'b')('a', 'b')
final
>>>>>>

 

同样可以处理多个异常筛选。

 

Code
>>>>>> try:
raise EOFError("aa", "bb")
except RuntimeError, e:
print "[RuntimeErro]: ", e
except EOFError, e:
print "[EOFError]: ", e
except Exception, e:
print "[Error]: ", e
finally:
print "final"


[EOFError]: (
'aa', 'bb')
final
>>>>>>

 

除了异常参数,我们还可以用sys的一些方法来获取异常信息。

 

Code
>>>>>> import sys
>>>>>> try:
raise RuntimeError("the runtime error raised")
except:
print sys.exc_info()


(
<type 'exceptions.RuntimeError'>, RuntimeError('the runtime error raised',), <traceback object at 0x00DC5CB0>)
>>>>>>

 

缺省情况下,异常类都继承自 Exception。

 

Code
>>>>>> class MyException(Exception):
pass

>>>>>> try:
raise MyException("My Exception raised!")
except:
print sys.exc_info()


(
<class '__main__.MyException'>, MyException('My Exception raised!',), <traceback object at 0x00DC58F0>)
>>>>>>
阅读(456) | 评论(0) | 转发(0) |
0

上一篇:weathermap 配置

下一篇:Python __init__方法

给主人留下些什么吧!~~