try: try_suite
except Exception1,Exception2,...,Argument: exception_suite
...... #other exception block
else: no_exceptions_detected_suite
finally: always_execute_suite
try…except…语句
try捕获了任何异常,都将交给except子句的exception block来处理
try … except…else语句
就是当没有检测到异常的时候,则执行else语句
finally子句
finally子句是无论是否检测到异常,都会执行的一段代码。我们可以丢掉except子句和else子句,单独使用try…finally,也可以配合except等使用。
assert语句用于检测表达式是否为真,如果为假,引发AssertionError错误;
语法格式:assert expression [,args]
expression:表达式
args:判断条件的描述信息
with open(r'somefileName') as somefile:for line in somefile:print line# ...more code
#!/usr/bin/python
# -*- coding: UTF-8 -*-# 定义函数
def mye( level ):if level < 1:raise Exception("Invalid level!", level)# 触发异常后,后面的代码就不会再执行try:mye(0) // 触发异常
except "Invalid level!":print 1
else:print 2
#输出结果
$ python test.py
Traceback (most recent call last):File "test.py", line 11, in <module>mye(0)File "test.py", line 7, in myeraise Exception("Invalid level!", level)
Exception: ('Invalid level!', 0)
本文发布于:2024-02-01 04:10:10,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170673181133756.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |