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
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)
While I agree that Jochen Ritzel's is a good answer, I think there may be a small oversight in it. By passing, 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 raised. 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)
do_something(); print("Message: ", line)?explicit is better than implicit. Any user will see that an except is expected, and then raised to the caller, without having to look up whether do_something raises any exceptions.else, closing acquired connections on finally, and letting the rest of your script handle an except as normal)