Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 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 Reply

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:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...