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

下面的方法是正确的吗?

try:
    shutil.rmtree(path)
except:
    pass

当前回答

在Python中,我们处理异常的方式与其他语言类似,但区别在于语法上的不同,例如,

try:
    #Your code in which exception can occur
except <here we can put in a particular exception name>:
    # We can call that exception here also, like ZeroDivisionError()
    # now your code
# We can put in a finally block also
finally:
    # Your code...

其他回答

try:
    doSomething()
except Exception: 
    pass

or

try:
    doSomething()
except: 
    pass

不同的是第二个也会捕捉KeyboardInterrupt, SystemExit和类似的东西,它们直接从BaseException派生,而不是Exception。

详见文档:

试着声明 异常

然而,捕捉每个错误通常是糟糕的实践——参见为什么“except: pass”是一个糟糕的编程实践?

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

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

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

在Python中,我们处理异常的方式与其他语言类似,但区别在于语法上的不同,例如,

try:
    #Your code in which exception can occur
except <here we can put in a particular exception name>:
    # We can call that exception here also, like ZeroDivisionError()
    # now your code
# We can put in a finally block also
finally:
    # Your code...

我通常会这样做:

try:
    doSomething()
except:
    _ = ""

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

这取决于你对“处理”的定义。

如果你想抓住它不采取任何行动,你张贴的代码将工作。

如果你的意思是你想对一个异常采取行动,而不阻止该异常上升到堆栈,那么你想要这样的东西:

try:
    do_something()
except:
    handle_exception()
    raise  #re-raise the exact same exception that was thrown