|
1 | 1 | ============================== |
2 | | -14.10 重新抛出最后的异常 |
| 2 | +14.10 重新抛出被捕获的异常 |
3 | 3 | ============================== |
4 | 4 |
|
5 | 5 | ---------- |
6 | 6 | 问题 |
7 | 7 | ---------- |
8 | | -You caught an exception in an except block, but now you want to reraise it. |
| 8 | +你在一个 ``except`` 块中捕获了一个异常,现在想重新抛出它。 |
9 | 9 |
|
10 | 10 | | |
11 | 11 |
|
12 | 12 | ---------- |
13 | 13 | 解决方案 |
14 | 14 | ---------- |
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 | + >>> |
32 | 34 |
|
33 | 35 | | |
34 | 36 |
|
35 | 37 | ---------- |
36 | 38 | 讨论 |
37 | 39 | ---------- |
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 |
50 | 53 |
|
0 commit comments