How to properly ignore exceptions

前端 未结 11 2133
粉色の甜心
粉色の甜心 2020-11-22 02:18

When you just want to do a try-except without handling the exception, how do you do it in Python?

Is the following the right way to do it?

try:
    s         


        
11条回答
  •  时光说笑
    2020-11-22 02:59

    For completeness:

    >>> def divide(x, y):
    ...     try:
    ...         result = x / y
    ...     except ZeroDivisionError:
    ...         print("division by zero!")
    ...     else:
    ...         print("result is", result)
    ...     finally:
    ...         print("executing finally clause")
    

    Also note that you can capture the exception like this:

    >>> try:
    ...     this_fails()
    ... except ZeroDivisionError as err:
    ...     print("Handling run-time error:", err)
    

    ...and re-raise the exception like this:

    >>> try:
    ...     raise NameError('HiThere')
    ... except NameError:
    ...     print('An exception flew by!')
    ...     raise
    

    ...examples from the python tutorial.

提交回复
热议问题