18

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
0

2 Answers 2

33

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) 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I will mark this answer as corrected in a few minutes (it is not possible for some minutes)
The question was to not handle the exception - better to use raise than pass.
18

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) 

7 Comments

Isn't that exactly identical to do_something(); print("Message: ", line)?
@KirkStrauser yes, but 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.
@Darthfett I think that's going overboard. If you think that an exception is likely to crop up, you should handle it properly (even if that's just printing a user-friendly message) otherwise, just leave it out.
Are you saying that if do_something() encounters an error internal to that function, you'd rather attempt to detect that outside of the function and then raise an exception, on its behalf, outside of the function call? That doesn't sound like a good idea.
Just to note: This format is indeed useful if you ever want to handle else AND finally, but allow exceptions to propagate unobstructed. (e.g. returning from function on else, closing acquired connections on finally, and letting the rest of your script handle an except as normal)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.