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)