Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

python - 如何正确忽略异常(How to properly ignore exceptions)

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

(如果您只是想尝试 - 除非不处理异常,您如何在Python中执行此操作?)

Is the following the right way to do it?

(以下是正确的方法吗?)

try:
    shutil.rmtree(path)
except:
    pass
  ask by Joan Venge translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
try:
  doSomething()
except: 
  pass

or

(要么)

try:
  doSomething()
except Exception: 
  pass

The difference is, that the first one will also catch KeyboardInterrupt , SystemExit and stuff like that, which are derived directly from exceptions.BaseException , not exceptions.Exception .

(不同的是,第一个也会捕获KeyboardInterruptSystemExit和类似的东西,它们直接派生自exceptions.BaseException ,而不是exceptions.Exception 。)
See documentation for details:

(有关详情,请参阅文档)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...