Python中的异常处理相关语句基础学习笔记
异常是指因为程序出现了错误而在正常控制流以外采取的行动,其分为两个阶段,第一阶段是引发异常的错误,当系统检测到错误并且意识到异常条件,解释器(也可以是程序员引发异常)会引发一个异常通知前段控制流有错误发生,对异常的处理发生在第二阶段,异常引发后,可以调用很多不同的操作,可以是忽略错误,或是记录错误但不采取任何措施,采取补救措施后终止程序,或是江青问题的影响后设法继续执行程序 >>> 1/0 Traceback (most recent call last): File "",line 1,in ZeroDivisionError: integer division or modulo by zero >>> raise [someException [,args [,traceback]]] try-except 语句 try: try_suite #进行监控的代码 except Exception[,reason]: except_suite #异常处理的代码 [except Exception2[,reson2]: except_suite2 # 处理try语句中可能发生的多种异常 [else: else_suite #try中语句执行没有异常被检测到 [finally: finally_suite #无论如何均会执行]]] try: try: try_suite except: excetp_suite finally: finally_suite 等效于: try: try_suite except: excetp_suite finally: finally_suite Assert Python中assert的运用于C语言中的assert()函数相似, assert expression1,expression2 (不用小括号) >>> a=10 >>> assert a<=10,"Error" >>> a = 11 >>> assert a<=10,"Error" Traceback (most recent call last): File "<stdin>",in <module> AssertionError: Error 等价于: if a>10: raise AssertionError("Error") 说明: python -0 test.py (这其实与C语言中的编译参数-d类似) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |