Python10
来源:互联网 发布:ubuntu wine安装 编辑:程序博客网 时间:2024/04/29 22:06
异常
异常可以通过try语句来检测,在try块里的代码都会被检测有无异常发生。try有两种主要形式:try-except 和try-finally,这两个相互排斥,只能选择其中一个。
try-except
try: code #待监控代码except Exception1[,reason1]: except_code1 #异常处理代码except Exception2[,reason2]: except_code2 #异常处理代码...
例:
>>> try:... handler=open('tmp','r')... except IOError as e:... print(e)... print(e.__class__)... print(e.__class__.__doc__)... print(e.__class__.__name__) ...[Errno 2] No such file or directory: 'tmp'<class 'FileNotFoundError'>File not found.FileNotFoundError
else & finally
在else范围中的任何代码运行前,try范围中的所有代码必须完全成功,而finally则是无论异常是否发生,是否捕获都会执行。
>>> try:... handle=open('tmp.info','r+')... except:... print('open error')... else:... print('open finish')... handle.close()... finally:... print('finally')...open errorfinally
assert
断言成功不采取任何措施,否则出发AssertionError异常,与c中assert类似。
assert expression[,arguments]
例:
>>> assert 1==0Traceback (most recent call last): File "<stdin>", line 1, in <module>AssertionError>>> assert 1==0,'One is not equal Zero'Traceback (most recent call last): File "<stdin>", line 1, in <module>AssertionError: One is not equal Zero>>> try:... assert 1==2,'One is not equal Two'... except AssertionError as e:... print('%s:%s' %(e.__class__.__name__,e))...AssertionError:One is not equal Two
标准异常
0 0