HiveBrain v1.2.0
Get Started
← Back to all entries
debugpythonCritical

How to properly ignore exceptions

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
exceptionshowproperlyignore

Problem

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

Is the following the right way to do it?

try:
    shutil.rmtree(path)
except:
    pass

Solution

try:
    doSomething()
except Exception: 
    pass


or

try:
    doSomething()
except: 
    pass


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

See documentation for details:

  • try statement



  • exceptions



However, it is generally bad practice to catch every error - see Why is "except: pass" a bad programming practice?

Code Snippets

try:
    doSomething()
except Exception: 
    pass
try:
    doSomething()
except: 
    pass

Context

Stack Overflow Q#730764, score: 1240

Revisions (0)

No revisions yet.