Python : Try

the try statement

try_stmt ::= try1_stmt | try2_stmt
try1_stmt ::= “try” “:” suite 
              (“except” [expression [“as” identifier]] “:” suite)+ 
              [“else” “:” suite] 
              [“finally” “:” suite] 
try2_stmt ::= “try” “:” suite 
              “finally” “:” suite
  • expression-less except

!Note: An expression-less except clause, if present, must be last; it matches any exception.(expression-less except: 缺少 expression 的 except: 即为 except:)

try:
  some code ...
except exc_A:
  some handle code ...
except exc_B:
  some handle code ...
except:            # the last
  some handle code ...
  • compatible

For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is “compatible” with the exception. An object is compatible with an exception if it is the class or a base class of the exception object or a tuple containing an item compatible with the exception.

  • So, all user-defined exceptions should also be derived from this class: Exception.
  • a tuple of exceptions
  expression ::= (exc_1, exc_2, ... , exc_N)
try:
        1/0
except (ZeroDivisionError, IOError) as e:
        print(str(e))
...
division by zero
  • as
    When a matching except clause is found, the exception is assigned to the target specified after the as keyword in that except clause
    When an exception has been assigned using as target, it is cleared at the end of the except clause. This is as if
except E as N:
    foo

was translated to

except E as N:
    try:
        foo
    finally:
        del N
  • else

The optional else clause is executed if and when control flows off the end of the try clause. Exceptions in the else clause are not handled by the preceding except clauses.

  • finally

If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception it is re-raised at the end of the finally clause. If the finally clause raises another exception, the saved exception is set as the context of the new exception.

>>> try:
...   1/0
... finally:
...   print("what's up?")
...   raise ValueError
... 
what's up?                          # print in finally statement
Traceback (most recent call last):          # re-raised and set as __context__ of ValueError()
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):          
  File "<stdin>", line 5, in <module>
ValueError

If the finally clause executes a return or break statement, the saved exception is discarded:

>>> def f():            
...     try:
...         1/0
...     finally:
...         return 42
...
>>> f()                # the saved exception is discarded.
42

The return value of a function is determined by the last return statement executed. Since the finally clause always executes, a return statement executed in the finally clause will always be the last one executed:

>>> def foo():
...   try:
...     return 'try'
...   finally:
...     return 'finally'
... 
>>> foo()
'finally'
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容