python中的异常

来源:互联网 发布:sql server字符串类型 编辑:程序博客网 时间:2024/06/09 16:18

1,空的except语句将会捕捉所有的异常,可以用sys模块中取出异常名和异常的值

2,raw_input()读文件到末尾时,会引发EOFError异常,这种异常不是错误

3,finally只做清楚工作,不做异常处理

异常处理的例子:

myException="Error"def raise1():   raise myException, "hello"def raise2():   raise myExceptiondef tryer(func):   try:      func()   except myException,extraInfo:      import  sys      print sys.exc_type      print "got this:",extraInfo

执行的例子:

from exc import *tryer(raise1)tryer(raise2)

报错:TypeError: exceptions must be old-style classes or derived from BaseException, not str

原因:In Python 2.5 and below, your code would work, as then it was allowed to raise strings as exceptions. This was a very bad decision, and so removed in 2.6.

改写后的例子:

class myException(Exception):   passdef raise1():   raise myException, "hello"def raise2():   raise myExceptiondef tryer(func):   try:      func()   except myException,extraInfo:      import  sys      print sys.exc_type      print "got this:",extraInfo

让自己编写的异常类全部继承于Exception顶级异常类就行了