Python Errors and Exceptions 官方文檔html
raise
關鍵字, raise either an exception instance or an exception class (a class that derives from Exception).raise NameError('wrong name')
Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: wrong name
class MyError(Exception): pass
try/except
關鍵字exception (NameError, TrancisionError, ValueError): pass
三個當中任意一個知足時,都會catch並處理except RuntimeError, TypeError
is not equivalent to except (RuntimeError, TypeError)
: but to except RuntimeError as TypeError
try關鍵字的執行流程:
The try statement works as follows.
First, the try clause (the statement(s) between the try and except keywords) is executed.
If no exception occurs, the except clause is skipped and execution of the try statement is finished.
If an exception occurs during the execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.
If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.python
異常當中的else語句: 執行沒有異常時須要作的事情
The try … except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example:json
try: <statements> # Run this main action first except <name1>: <exc1> # 當 try中發生了 name1 的異常時運行exc1 except <name2>: <exc2> # 當 try中發生了 name2 的異常時運行exc2 except (<name3>, <name4>: <exc3> # 當 try中發生了 name3 OR name4 的異常時運行exc3 else: <exc4> # 當代碼沒有異常時運行exc4 finally: <final> #無論代碼有沒有異常都會執行final, 一般用來作一些清理工做
import sys try: print a b = 0 print a / b except: sys.exit("ZeroDivisionError:Can not division zero")程序打印"ZeroDivisionError: Can not division zero", 可是這不是真正的錯誤緣由, 真正的錯誤緣由是a 在使用以前沒有進行定義
raise
關鍵字便可。大類錯誤能夠捕捉子類中的錯誤【25/91建議】避免finally 可能發生的陷阱:dom
return
或 break
語句時, 臨時保存的異常 和 try當中本來被設計好的return語句將被丟失def ReturnTest(a): try: if a <= 0: raise ValueError("data can not be negative") else: return a except ValueError as e: print e finally: print("The End!") return -1 print ReturnTest(0) # 輸出"The End!" "-1" print ReturnTest(1) # 輸出"The End!" "-1" 出現問題
finally 當中的return在try 中的else 語句以前執行, 因此會直接運行 finally 當中的return -1
而不是try 當中的 return a
ide
try/finally
結構: 若是既要將異常向上傳播, 又要在異常發生時進行清理工做handle = open('/tmp/random_data.txt') # May raise IOError try: data = handle.read() # May raise UnicodeDecode Error finally: handle.close() # Always runs after try
try/except/else
結構: 清晰描述哪些異常由本身的代碼處理、哪些異常會傳給上一級。若是try
代碼中沒有發生異常, 那麼就執行else
語句, 有了這種else 語句, 咱們就能夠儘可能縮減try中的代碼量。def load_json_key(data, key): try: result_dict = json.loads(data) # 嘗試讀取一個JSON文件 except ValueError as e: raise KeyError from e # 若是代碼不是有效的JSON格式, 會產生ValueError else: return result_dict[key] # 代碼是有效的JSOn格式, 進行處理
def divide_json(path): handle = open(path, 'r+') try: data = handle.read() op = json.loads(data) value = ( op['numerator'] / op['denominator']) # May raise ZeroDivisionError except ZeroDivisionError as e: return UNDEFINED else: op['result'] = value result = json.dumps(op) handle.seek(0) handle.write(result) # May raise IOError return value finally: handle.close() # Always runs
def main(): try: bar('0') except Exception as e: logging.exception(e)