Skip to content

Commit 5e99cd2

Browse files
committed
14.10小节完成
1 parent 5923711 commit 5e99cd2

File tree

1 file changed

+34
-31
lines changed

1 file changed

+34
-31
lines changed
Lines changed: 34 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,53 @@
11
==============================
2-
14.10 重新抛出最后的异常
2+
14.10 重新抛出被捕获的异常
33
==============================
44

55
----------
66
问题
77
----------
8-
You caught an exception in an except block, but now you want to reraise it.
8+
你在一个 ``except`` 块中捕获了一个异常,现在想重新抛出它。
99

1010
|
1111
1212
----------
1313
解决方案
1414
----------
15-
Simply use the raise statement all by itself. For example:
16-
17-
>>> def example():
18-
... try:
19-
... int('N/A')
20-
... except ValueError:
21-
... print("Didn't work")
22-
... raise
23-
...
24-
25-
>>> example()
26-
Didn't work
27-
Traceback (most recent call last):
28-
File "<stdin>", line 1, in <module>
29-
File "<stdin>", line 3, in example
30-
ValueError: invalid literal for int() with base 10: 'N/A'
31-
>>>
15+
简单的使用一个单独的 ``rasie`` 语句即可,例如:
16+
17+
::
18+
19+
>>> def example():
20+
... try:
21+
... int('N/A')
22+
... except ValueError:
23+
... print("Didn't work")
24+
... raise
25+
...
26+
27+
>>> example()
28+
Didn't work
29+
Traceback (most recent call last):
30+
File "<stdin>", line 1, in <module>
31+
File "<stdin>", line 3, in example
32+
ValueError: invalid literal for int() with base 10: 'N/A'
33+
>>>
3234

3335
|
3436
3537
----------
3638
讨论
3739
----------
38-
This problem typically arises when you need to take some kind of action in response to
39-
an exception (e.g., logging, cleanup, etc.), but afterward, you simply want to propagate
40-
the exception along. A very common use might be in catch-all exception handlers:
41-
42-
try:
43-
...
44-
except Exception as e:
45-
# Process exception information in some way
46-
...
47-
48-
# Propagate the exception
49-
raise
40+
这个问题通常是当你需要在捕获异常后执行某个操作(比如记录日志、清理等),但是之后想将异常传播下去。
41+
一个很常见的用法是在捕获所有异常的处理器中:
42+
43+
.. code-block:: python
44+
45+
try:
46+
...
47+
except Exception as e:
48+
# Process exception information in some way
49+
...
50+
51+
# Propagate the exception
52+
raise
5053

0 commit comments

Comments
 (0)