views:

23246

answers:

5

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

try :
    shutil.rmtree ( path )
except :
    pass
+23  A: 
vartec
Note that StopIteration and Warning both inherit from Exception as well. Depending on your needs, you may want to inherit from StandardError instead.
Ben Blank
@Ben: both of these are "normal" exceptions, so no problem there..
vartec
This is true, but if you're not careful, you can run into subtle bugs (especially if you're doing something other than passing on StopIteration).
Jason Baker
+12  A: 

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

It depends on what you mean by "handling."

If you mean to catch it without taking any action, the code you posted will work.

If you mean that you want to take action on an exception without stopping the exception from going up the stack, then you want something like this:

try:
    do_something()
except:
    handle_exception()
    raise  #re-raise the exact same exception that was thrown
Jason Baker
+1 nice addition to the thread of answers
Jarret Hardie
+5  A: 

It's generally considered best-practice to only catch the errors you are interested in, in the case of shutil.rmtree it's probably OSError:

>>> shutil.rmtree("/fake/dir")
Traceback (most recent call last):
    [...]
OSError: [Errno 2] No such file or directory: '/fake/dir'

If you want to silently ignore that error, you would do..

try:
    shutil.rmtree(path)
except OSError:
    pass

Why? Say you (somehow) accidently pass the function an integer instead of a string, like..

shutil.rmtree(2)

It will give the error "TypeError: coercing to Unicode: need string or buffer, int found" - you probably don't want to ignore that, which can be difficult to debug..

If you defiantly want to ignore all errors, catch Exception rather than a bare catch: statement. Again, why?

It catches every exception, include the SystemExit exception which sys.exit() uses, for example:

>>> try:
...     sys.exit(1)
... except:
...     pass
... 
>>>

..compared to the following, which correctly exits:

>>> try:
...     sys.exit(1)
... except Exception:
...     pass
... 
shell:~$
dbr
This is the only answer to mention the most important point: silently trashing all exceptions is almost always a terrible idea.
Carl Meyer
+1  A: 
try:
      doSomething()
except Exception: 
    pass
else:
      stuffDoneIf()
      TryClauseSucceeds()

FYI the else clause can go after all exceptions and will only be run if the code in the try doesn't cause an exception.

MrChrisRodriguez
+2  A: 

For completeness:

>>> def divide(x, y):
...     try:
...         result = x / y
...     except ZeroDivisionError:
...         print "division by zero!"
...     else:
...         print "result is", result
...     finally:
...         print "executing finally clause"

...from the python tutorial.

cbare