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 閱讀(652) 評論(0)  編輯  收藏 所屬分類: python

          常用鏈接

          留言簿(21)

          隨筆分類(265)

          隨筆檔案(242)

          相冊

          JAVA網站

          關注的Blog

          搜索

          •  

          積分與排名

          • 積分 - 914107
          • 排名 - 40

          最新評論

          主站蜘蛛池模板: 湟源县| 锦屏县| 德庆县| 遂平县| 红河县| 枣阳市| 饶平县| 阿荣旗| 彭山县| 永丰县| 宣汉县| 汽车| 蚌埠市| 马边| 高邮市| 南靖县| 恩平市| 万源市| 蒙自县| 刚察县| 昭苏县| 白水县| 博客| 安西县| 望谟县| 罗山县| 孝义市| 澎湖县| 庆城县| 濮阳市| 乌拉特中旗| 陵川县| 水城县| 高青县| 文山县| 喀喇沁旗| 合川市| 洮南市| 江北区| 昭苏县| 隆尧县|