Python學習記錄八---異常

異常
Python用異常對象(exception object)來表示異常狀況。遇到錯誤後,會引起異常。若是異常對象並未被處理或捕捉,程序就會用所謂的回溯(Traceback,一種錯誤信息)終止執行。函數

一、raise語句
  >>> raise Exception
  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
  Exceptionthis

  >>> raise Exception("error error error!")
  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
  Exception: error error error!對象

二、重要的內建異常類:索引

  Exception : 全部異常的基類
  AttributeError: 特性引用或賦值失敗時引起
  IOError: 試圖打開不存在的文件(包括其餘狀況)時引起
  IndexError: 在使用序列中不存在的索引時引起
  KeyError:在使用映射序列中不存在的鍵時引起
  NameError:在找不到名字(變量)時引起
  SyntaxError:在代碼爲錯誤形式時引起
  TypeError:在內建操做或者函數應用於錯誤類型的對象時引起
  ValueError:在內建操做或者函數應用於正確類型的對象, 可是該對象使用不合適的值時引起
  ZeroDibivionError:在除法或者模除操做的第二個參數爲0時引起input

三、自定義異常類
  class SubclassException(Exception):passio

四、捕捉異常
使用 try/except

  >>> try:
  ...      x = input('Enter the first number:')
  ...      y = input('Enter the second number:')
  ...      print x/y
  ...  except ZeroDivisionError:
  ...     print "the second number can't be zero!"
  ...
Enter the first number:2
Enter the second number:0
the second number can't be zero!ast

五、捕捉對象class

  try:
    x = input('Enter the first number:')
    y = input('Enter the second number:')
    print x/y
  except (ZeroDivisionError, TypeError), e:
    print e變量

# 運行輸出
Enter the first number:4
Enter the second number:'s'
unsupported operand type(s) for /: 'int' and 'str'module

六、所有捕捉
  try:
    x = input('Enter the first number:')
    y = input('Enter the second number:')
    print x/y
  except:
    print "Something was wrong"

七、try/except else:
else在沒有異常引起的狀況下執行

  try:
    x = input('Enter the first number:')
    y = input('Enter the second number:')
    print x/y
  except:
    print "Something was wrong"
  else:
    print "this is else"

# 執行後的輸出結果
Enter the first number:3
Enter the second number:2
1
this is else

八、finally
能夠用在可能異常後進行清理,和try聯合使用

  try:     x = input('Enter the first number:')     y = input('Enter the second number:')     print x/y   except (ZeroDivisionError, TypeError), e:     print e   else:     print "this is else"   finally:     print "this is finally"

相關文章
相關標籤/搜索