Python 带有空的 except 代码的 Try-except 子句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24249298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:18:10  来源:igfitidea点击:

Try-except clause with an empty except code

pythontry-except

提问by Ehsan88

Sometimes you don't want to place any code in the exceptpart because you just want to be assured of a code running without any error but not interested to catch them. I could do this like so in C#:

有时您不想在except零件中放置任何代码,因为您只想确保代码运行时没有任何错误,但不想捕获它们。我可以在 C# 中这样做:

try
{
 do_something()
}catch (...) {}

How could I do this in Python ?, because the indentation doesn't allow this:

我怎么能在 Python 中做到这一点?,因为缩进不允许这样做:

try:
    do_something()
except:
    i_must_enter_somecode_here()

BTW, maybe what I'm doing in C# is not in accordance with error handling principles too. I appreciate it if you have thoughts about that.

顺便说一句,也许我在 C# 中所做的也不符合错误处理原则。如果您对此有想法,我将不胜感激。

回答by Andy

try:
    do_something()
except:
    pass

You will use the passstatement.

您将使用pass语句。

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.

pass 语句什么都不做。它可以在语法上需要语句但程序不需要操作时使用。

回答by Dmitry Savy

try:
  doSomething()
except: 
  pass

or you can use

或者你可以使用

try:
  doSomething()
except Exception: 
  pass

回答by A.J. Uppal

Use pass:

使用pass

try:
    foo()
except: 
    pass

A passis just a placeholder for nothing, it just passes along to prevent SyntaxErrors.

Apass只是一个无用的占位符,它只是传递以防止 SyntaxErrors。