異常
程序執行過程中遇到問題無法繼續,這個問題就是異常。這些異常可能是程序員在編寫程序時的疏忽或者考慮不周所致,也可由程序員根據需要自定義、拋出異常。通過閱讀異常信息,我們可以改進程序,排除自己不想要的結果,也可提示信息,提高用戶體驗。
內置異常及層次結構:
<code>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 +-- ResourceWarning/<code>
源自:https://docs.python.org/3/library/exceptions.html#base-classes
異常處理
異常必須進行處理,否則程序無法繼續運行。
簡單來說,異常處理過程分3步:產生(拋出)異常-->檢測並捕獲異常-->處理異常
- 基本應用(try...except...)
<code># 檢測異常 try: pass # 捕獲異常並處理異常 except: pass/<code>
例:
<code># 除數為0的錯誤 a = 1 b = 0 c = a / b/<code>
報錯:ZeroDivisionError: division by zero
<code># 發生異常時捕獲異常並提示 # 程序不終止執行 try: a = 1 b = 0 c = a / b except: print('Some exception occurs!')/<code>
- 獲取異常信息(try...except Exception as e...)
<code>try: a = 1 b = 0 c = a / b except Exception as e: print('Some exception occurs!-->', e)/<code>
- 沒有異常時執行某操作(try...except...else...)
<code>def op(a, b): r = a / b return r c = None try: a = 1 b = 2 c = op(a, b) except Exception as e: print('Some exception occurs!-->', e) else: print('Result is: ', c)/<code>
- 不管有沒有異常都要執行某操作(try...except..finally...)
<code>def op(a, b): r = a / b return r c = None try: a = 1 b = 0 c = op(a, b) except Exception as e: print('Some exception occurs!-->', e) else: print('Result is: ', c) finally: print('Operation done.')/<code>
注意如果其中有return時的返回值情況:
<code>try: return 1 except: return 2 finally: return 3/<code>
結果:無論有沒有Exception都返回3
自定義觸發異常
使用raise語句自定義觸發異常
<code>def func(i): if i < 0: raise Exception('數量不能為負。') try: func(-1) except Exception as e: print(e)/<code>
自定義異常
通過繼承的方式創建自己的異常類,使用方式與內置異常類相同。
<code>class UserExcption(Exception): def __init__(self, arg): self.args = arg try: raise UserExcption('User defined exception.') except UserExcption as e: print(e)/<code>