Python – Try-except , else & finally statement

Loading

測試環境為 CentOS 8 x86_64 (虛擬機)

Try-except statement 格式如下,通常會搭配 raise exception – https://benjr.tw/104314 來使用.

try:
  # 執行以下區塊的程式碼.
except 例外名稱:
  # 如 Try 區塊內的程式碼無法正確執行時則執行 Except 內容(可以指定 Except 錯誤名稱).
except:
  # 如 Try 區塊內的程式碼無法正確執行時則執行 Except 內容.
else:
  # 如 Try 區塊內的程式碼並未發生錯誤時執行 ELSE 區塊內的程式碼.
finally:
  # 不管 Try 區塊內的程式碼是否可以正確執行都要執行 Finally 區塊內的程式碼.

下面範例輸入兩整數,並透過 Try-except 來避免錯誤發生.

[root@localhost ~]# vi try.py
try:
    a=int(input("Input a number:" ))
    b=int(input("Input a number:" ))
    c=a/b
except ZeroDivisionError:
    print('Division by zero')
except Exception as e:
    print(e)
else:
    print(a , "/" , b ,"=" ,c)
finally:
    print("Complete")
  • except ZeroDivisionError:
    因為有發生 ZeroDivisionError 所以執行 except ZeroDivisionError 區塊.

    [root@localhost ~]# python3 try.py
    Input a number:1
    Input a number:0
    Division by zero
    Complete
    

    關於 exceptions 例外名稱請參考官方網站 – https://docs.python.org/3/library/exceptions.html , 下面是所有的 exceptions 的階層.

    BaseException
     +-- SystemExit
     +-- KeyboardInterrupt
     +-- GeneratorExit
     +-- Exception
          +-- StopIteration
          +-- StopAsyncIteration
          +-- ArithmeticError
          |    +-- FloatingPointError
          |    +-- OverflowError
          |    +-- ZeroDivisionError
          +-- AssertionError
          +-- AttributeError
          +-- BufferError
          +-- EOFError
          +-- ImportError
          |    +-- ModuleNotFoundError
          +-- LookupError
          |    +-- IndexError
          |    +-- KeyError
          +-- MemoryError
          +-- NameError
          |    +-- UnboundLocalError
          +-- OSError
          |    +-- BlockingIOError
          |    +-- ChildProcessError
          |    +-- ConnectionError
          |    |    +-- BrokenPipeError
          |    |    +-- ConnectionAbortedError
          |    |    +-- ConnectionRefusedError
          |    |    +-- ConnectionResetError
          |    +-- FileExistsError
          |    +-- FileNotFoundError
          |    +-- InterruptedError
          |    +-- IsADirectoryError
          |    +-- NotADirectoryError
          |    +-- PermissionError
          |    +-- ProcessLookupError
          |    +-- TimeoutError
          +-- ReferenceError
          +-- RuntimeError
          |    +-- NotImplementedError
          |    +-- RecursionError
          +-- SyntaxError
          |    +-- IndentationError
          |         +-- TabError
          +-- SystemError
          +-- TypeError
          +-- ValueError
          |    +-- UnicodeError
          |         +-- UnicodeDecodeError
          |         +-- UnicodeEncodeError
          |         +-- UnicodeTranslateError
          +-- Warning
               +-- DeprecationWarning
               +-- PendingDeprecationWarning
               +-- RuntimeWarning
               +-- SyntaxWarning
               +-- UserWarning
               +-- FutureWarning
               +-- ImportWarning
               +-- UnicodeWarning
               +-- BytesWarning
               +-- EncodingWarning
               +-- ResourceWarning
    
  • except Exception as e:
    發生非 ZeroDivisionError 錯誤所以執行 except Exception as e 區塊.這邊會建立 名稱為 e 物件 (Object) 的 Exception 類別 (class) .

    [root@localhost ~]# python3 try.py
    Input a number:1
    Input a number:y
    invalid literal for int() with base 10: 'y'
    Complete
    

    可以透過 e 物件 (Object) 得知更多的錯誤訊息.

    print(f"{type(e).__name__} at line {e.__traceback__.tb_lineno} of {__file__}: {e}")
    
    [root@localhost ~]# vi try.py
    try:
        a=int(input("Input a number:" ))
        b=int(input("Input a number:" ))
        c=a/b
    except ZeroDivisionError:
        print('Division by zero')
    except Exception as e:
        print(e)
        print(f"{type(e).__name__} at line {e.__traceback__.tb_lineno} of {__file__}: {e}")
    else:
        print(a , "/" , b ,"=" ,c)
    finally:
        print("Complete")
    

    執行結果.

    [root@localhost ~]# python3 try.py
    Input a number:1
    Input a number:w
    invalid literal for int() with base 10: 'w'
    ValueError at line 3 of try.py: invalid literal for int() with base 10: 'w'
    Complete
    
  • else:
    如錯誤發生會執行 else 區塊.

    [root@localhost ~]# python3 try.py
    Input a number:1
    Input a number:2
    1 / 2 = 0.5
    Complete
    
  • finally:
    不管前面是否出現錯誤,最後都會執行這一區塊,也就是列印出字串 Complete .

    [root@localhost ~]# python3 try.py
    Input a number:1
    Input a number:2
    1 / 2 = 0.5
    Complete
    
沒有解決問題,試試搜尋本站其他內容

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料