Rox
Rox

Reputation: 2917

Python: try-catch-else without handling the exception. Possible?

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

Answers (2)

Jochen Ritzel
Jochen Ritzel

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

inspectorG4dget
inspectorG4dget

Reputation: 113915

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) 

Upvotes: 18

Related Questions