Skip to content

Commit a7793b3

Browse files
committed
Updates Python异常.md
Auto commit by GitBook Editor
1 parent b1c139d commit a7793b3

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

Python异常.md

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ Python的运行时错误称作异常:
66
- 语法错误:软件的结构上有错误而导致不能被解释器解释或不能被编译器编译;
77

88
- 逻辑错误:由于不完整或不合法的输入导致,也可以是逻辑无法生成、计算或者输出结果需要的过程无法执行等。
9+
910
```python
1011
In [1]: f1 = open('/tmp/a.txt')
1112
---------------------------------------------------------------------------
@@ -25,11 +26,15 @@ TypeError Traceback (most recent call last)
2526

2627
TypeError: Can't convert 'int' object to str implicitly
2728
```
29+
2830
异常的发生,会导致程序执行终止;
2931

3032
### python异常:
33+
3134
python异常是一个对象,表示错误或意外情况;
35+
3236
在python检测到一个错误时,将触发一个异常;
37+
3338
- python可以通过异常传导机制传递一个异常对象,发出一个异常情况出现的信号;
3439
- 程序员也可以在代码中手动触发异常;
3540

@@ -107,19 +112,28 @@ else:
107112
```
108113

109114
except分句个数没有限制,但else只能有一个;
115+
110116
没有异常发生时,else分句才会执行;
117+
111118
没有符合的except分句时,异常会向上传递到程序中的之前进入的try语句中或者到进程的顶层(解释器);
112119

120+
113121
### try-finally语句
122+
114123
无论异常是否发生,finally子句都会执行;
124+
115125
常用语定义必须进行的清理动作,如关闭文件或断开服务器连接等;
126+
116127
finally中的所有代码执行完毕后会继续向上一层引发异常;
117128

118129
语法:
130+
131+
```python
119132
try:
120133
try_suite
121134
finally:
122135
finally_suite
136+
```
123137

124138
```python
125139
In [5]: try:
@@ -131,7 +145,8 @@ In [5]: try:
131145
...: f1.close()
132146
...:
133147
...:
134-
('There is some problem for write statement to file /tmp/a.txt.', IOError(2, 'No such file or directory'))
148+
('There is some problem for write statement to file /tmp/a.txt.',
149+
IOError(2, 'No such file or directory'))
135150
---------------------------------------------------------------------------
136151
NameError Traceback (most recent call last)
137152
<ipython-input-5-04febf19ca2a> in <module>()
@@ -180,6 +195,7 @@ finally:
180195
可以替换为在try-finally语句中嵌套try-except语句的形式;
181196

182197
### try语句嵌套:
198+
```python
183199
try:
184200
try:
185201
try_suite
@@ -188,6 +204,7 @@ try:
188204
else:
189205
finally:
190206
suite_finally
207+
```
191208

192209

193210
### 自定义异常:

0 commit comments

Comments
 (0)