Reputation: 3151
if os.path.exists(temp_dir):
print "Deleting ", temp_dir
try:
shutil.rmtree(temp_dir)
except:
raise
print "Delete complete"
it prints "Deleting c:\temp\metabuild" but neither prints any error nor "Delete complete", obviously the rmtree failed, but want it to print what the error is, will "raise" print what the error is or no? thanks in advance!
Upvotes: 0
Views: 7575
Reputation: 365707
will "raise" print what the error is or no?
No, all raise
does is re-raise the exception, as if you hadn't caught it in the first place. In particular, this code:
try:
shutil.rmtree(temp_dir)
except:
raise
… is guaranteed to do the same thing (except slightly slower and a lot less readably) as:
shutil.rmtree(temp_dir)
If the exception ultimately propagates up to the top level without being handled anywhere, Python will print a traceback and exit. But if some other code handles the exception anywhere on the chain, it can do anything it wants.
If you want to print the exception out, you have to do that explicitly. For example:
try:
shutil.rmtree(temp_dir)
except Exception as e:
print(e)
raise
If you want more information than print(e)
or print(repr(e))
gives you, see the traceback
library, which has all kinds of functions for retrieving or dumping information about the exception and its traceback. In particular, to get the same output you would have gotten if this happened at the top level, do this:
try:
shutil.rmtree(temp_dir)
except Exception as e:
traceback.print_exc()
raise
Because print_exc
gets the exception object and other info directly out of Python's guts, you don't really need the except Exception as e:
here; you could just use except Exception:
or except:
.
Upvotes: 3