Python 学习笔记(三)

异常部分。

1.          处理异常

Eg

import sys

try:

    f = open('myfile.txt')

    s = f.readline()

    i = int(s.strip())

except IOError, (errno, strerror):

    print "I/O error(%s): %s" % (errno, strerror)

except ValueError:

    print "Could not convert data to an integer."

except:

    print "Unexpected error:", sys.exc_info()[0]

    raise

java 对比,差不多的用法。只是他不存在花括号。以冒号和缩进进行的作用域封装。还有就是 except 类似 java c++ 中的 catch

try ... except 语句可以带有一个 else 子句, 该子句只能出现在所有 except 子句之后。当 try 语句没有抛出异常时,需要执行一些代码,可以使用这个子句。例如:

for arg in sys.argv[1:]:

    try:

        f = open(arg, 'r')

    except IOError:

        print 'cannot open', arg

    else:

        print arg, 'has', len(f.readlines()), 'lines'

        f.close()

2.          抛出异常

Eg

try:

    raise NameError, 'HiThere'

except NameError,a:

    print 'An exception flew by!'

    #raise

    print type(a)

print a.args

主要函数 raise , 该函数第一个参数是异常名,第二个是这个异常的实例,它存储在 instance.args 的参数中。

except NameError,a: 中第二个参数意思差不多。

3.          用户自定义异常

class MyError(Exception):

    def __init__(self, value):

        self.value = value

    def __str__(self):

      return repr(self.value)

try:

  raise MyError(2*2)

except MyError, e:

  print 'My exception occurred, value:', e.value

异常类中可以定义任何其它类中可以定义的东西,但是通常为了保持简单,只在其中加入几个属性信息,以供异常处理句柄提取。如果一个新创建的模块中需要抛出几种不同的错误时,一个通常的作法是为该模块定义一个异常基类,然后针对不同的错误类型派生出对应的异常子类。

Eg:

class Error(Exception):

    """Base class for exceptions in this module."""

    pass

 

class InputError(Error):

    """Exception raised for errors in the input.

 

    Attributes:

        expression -- input expression in which the error occurred

        message -- explanation of the error

    """

 

    def __init__(self, expression, message):

        self.expression = expression

        self.message = message

 

class TransitionError(Error):

    """Raised when an operation attempts a state transition that's not

    allowed.

 

    Attributes:

        previous -- state at beginning of transition

        next -- attempted new state

        message -- explanation of why the specific transition is not allowed

    """

 

    def __init__(self, previous, next, message):

        self.previous = previous

        self.next = next

        self.message = message

4.          定义清理行为

try 语句还有另一个可选的子句,目的在于定义在任何情况下都一定要执行的功能。例如:

>>> try:

...     raise KeyboardInterrupt

... finally:

...     print 'Goodbye, world!'

...

Goodbye, world!

Traceback (most recent call last):

  File "<stdin>", line 2, in ?

KeyboardInterrupt

不管 try 子句中有没有发生异常, finally 子句都一定会被执行。如果发生异常,在 finally 子句执行完后它会被重新抛出。 try 子句经由 break return 退出也一样会执行 finally 子句。

try 语句中可以使用若干个 except 子句或一个 finally 子句,但两者不能共存。

posted on 2008-04-10 15:04 -274°C 阅读(639) 评论(0)  编辑  收藏 所属分类: python

只有注册用户登录后才能发表评论。


网站导航:
 

常用链接

留言簿(21)

随笔分类(265)

随笔档案(242)

相册

JAVA网站

关注的Blog

搜索

  •  

积分与排名

  • 积分 - 908981
  • 排名 - 40

最新评论