Reputation: 2917
I am new to python and is wondering if I can make a try-catch-else statement without handling the exception?
Like:
try:
do_something()
except Exception:
else:
print("Message: ", line) // complains about that else is not intended
Upvotes: 18
Views: 13748
Reputation: 107608
The following sample code shows you how to catch and ignore an exception, using pass.
try:
do_something()
except RuntimeError:
pass # does nothing
else:
print("Message: ", line)
Upvotes: 33
Reputation: 113915
While I agree that Jochen Ritzel's is a good answer, I think there may be a small oversight in it. By pass
ing, the exception /is/ being handled, only nothing is done. So really, the exception is ignored.
If you really don't want to handle the exception, then the exception should be raise
d. The following code makes that change to Jochen's code.
try:
do_something()
except RuntimeError:
raise #raises the exact error that would have otherwise been raised.
else:
print("Message: ", line)
Upvotes: 18