歡迎您光臨本站 註冊首頁

python怎麼自定義捕獲錯誤

←手機掃碼閱讀     retouched @ 2020-06-30 , reply:0

異常捕捉:

  try:     XXXXX1    raise Exception(“xxxxx2”)   except (Exception1,Exception2,……):     xxxx3  else:    xxxxx4  finally:    xxxxxxx5

 

1.raise 語句可以自定義報錯信息,如上。

2. raise後的語句是不會被執行了,因為已經拋出異常,控制流將會跳到異常捕捉模塊。

3. except 語句可以一個except後帶多個異常,也可以用多個語句捕捉多個異常,分別做不同處理。

4. except語句捕捉的異常如果沒有發生,那麼except裡的語句塊是不被執行的。而是執行else裡的語句

5. 在上面語句中try/except/else/finally所出現的順序必須是try�C>except X�C>except�C>else�C>finally,即所有的except必須在else和finally之前,else(如果有的話)必須在finally之前,而except X必須在except之前。否則會出現語法錯誤。

6.else和finally都是可選的.

7.在上面的完整語句中,else語句的存在必須以except X或者except語句為前提,如果在沒有except語句的try block中使用else語句會引發語法錯誤。

異常參數輸出:

  try:    testRaise()  except PreconditionsException as e: #python3的寫法,必須用as    print (e)

 

自定義異常,只需自定義異常類繼承父類Exception。在自定義異常類中,重寫父類init方法。

  class DatabaseException(Exception):    def __init__(self,err='數據庫錯誤'):      Exception.__init__(self,err)  class PreconditionsException(DatabaseException):    def __init__(self,err='PreconditionsErr'):      DatabaseException.__init__(self,err)  def testRaise():    raise PreconditionsException()  try:    testRaise()  except PreconditionsException as e:    print (e)

 

注意:PreconditonsException又是DatabaseException的子類。

所以如果,raise PreconditionException的話,用兩個異常類都可以捕捉。

但是, 如果是raise DatabaseException, 用PreconditonsException是捕捉不到的。

實例補充:

python自定義異常捕獲異常處理異常

  def set_inf(name,age):    if not 0 < age < 120:      raise ValueError('超出範圍')    else:      print('%s is %s years old' % (name,age))  def set_inf2(name,age):    assert 0 < age < 120,'超出範圍'    print('%s is %s years old' % (name,age))  if __name__ == '__main__':    try:     set_inf('bob',200)    except ValueError as e:      print('無效值:',e)    set_inf2('bob',200)

   


[retouched ] python怎麼自定義捕獲錯誤已經有240次圍觀

http://coctec.com/docs/python/shhow-post-240412.html