当你只想做一个try-except而不处理异常时,你在Python中如何做呢?

下面的方法是正确的吗?

try:
    shutil.rmtree(path)
except:
    pass

当前回答

我通常会这样做:

try:
    doSomething()
except:
    _ = ""

其他回答

try:
      doSomething()
except Exception: 
    pass
else:
      stuffDoneIf()
      TryClauseSucceeds()

供您参考,else子句可以放在所有异常之后,只有在try中的代码没有导致异常时才会运行。

首先我引用Jack o'Connor的回答。引用的线程已经关闭,所以我在这里写道:

“在Python 3.4中有一种新的方法可以做到这一点:

from contextlib import suppress

with suppress(Exception):
    # your code

下面是添加它的提交:http://hg.python.org/cpython/rev/406b47c64480

这里是作者Raymond Hettinger,他谈到了这个和其他各种Python热点:https://youtu.be/OSGv2VnC0go?t=43m23s

我对它的补充是Python 2.7的等效:

from contextlib import contextmanager

@contextmanager
def ignored(*exceptions):
    try:
        yield
    except exceptions:
        pass

然后像在Python 3.4中那样使用它:

with ignored(Exception):
    # your code

好吧,这不是一个try-except,但仍然是另一种处理异常的方法,如果你是面向对象编程:

class MyExceptionHandler:

    def __enter__(self):
        ... # Do whatever when "with" block is started
        return self

    def __exit__(self, exc_type, exc_value, tb):
        return True

然后是实际的代码:

with MyExceptionHandler():
     ... # Code that may or may not raise an exception
     shutil.rmtree(path)

这是怎么回事?

__enter__在进入with块时运行。 __exit__在退出with块时运行 这应该返回True以关闭可能的异常。 这应该返回None(或被认为是False的东西),以避免关闭潜在的异常。 异常类型、实际异常及其回溯作为(位置)参数传递。你可以用这些来决定要做什么。

最后要注意的是,更喜欢try-except。如果您需要比平时更多的抽象,这可能会很有用。

完整性:

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

还要注意,你可以像这样捕获异常:

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

...并像这样重新抛出异常:

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

此外,多种异常类型可以作为圆括号元组来处理:

try:
    i_might_fail()
except (ValueError, TypeError) as ex:
    print('I failed with: ', ex)

...或作为单独的除条款:

try:
    i_might_fail()
except ValueError:
    print('handling a ValueError...')
except TypeError:
    print('handling a TypeError...')

...请参阅python教程。

当你只想做一个try catch而不处理异常时, 用Python怎么做?

这将帮助你打印异常是什么:(即尝试catch而不处理异常并打印异常。)

import sys
try:
    doSomething()
except:
    print "Unexpected error:", sys.exc_info()[0]