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 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With