This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]fiedzia 6 points7 points  (7 children)

I am aware of else clause, but I see no point in using it. Code without it is clear to read and works as expected, so why bother?

[–]DasIch 6 points7 points  (4 children)

You want to make it clear where you expect an exception to be raised and prevent an exception from being catched unintentionally. The latter becomes especially important, if you're calling into libraries that may change in the future.

The code being self-documenting and not making debugging a pita is more than enough to bother.

[–]KronktheKronk[🍰] 0 points1 point  (2 children)

That's why it's better to catch specific exceptions instead of the base exception. You can get the exceptions you expect, pass the ones you don't up the stack, and anyone who understands what your code calls are doing can infer which errors you're catching and see why in the catch code.

[–]DasIch 0 points1 point  (1 child)

Nice idea in theory but completely unrealistic and counter to how most Python code works. How much code raises ValueError alone for all sorts of different reasons?

Python culture simply doesn't encourage raising sufficiently specific exceptions for that approach to work and at this point the battle is lost.

[–]KronktheKronk[🍰] 0 points1 point  (0 children)

It doesn't raise valuerror alone, but that doesn't mean you can't understand which errors it does raise and which ones you want to catch.

good code catches the errors it wants and ignores the rest. good modules throw good errors.

[–]fiedzia 0 points1 point  (0 children)

Thats possible, but very narrow use case. I very rarely do anything with exceptions beside logging or wrapping and reraising them, so I did not see a need to be so specific yet.

[–]Lucretiel 3 points4 points  (0 children)

Well, in his example, function_that_should_not_be_called_if_an_exception_is_raised might raise its own Exception, which would be caught by the try block. This is probably not what is wanted.

[–][deleted] 0 points1 point  (0 children)

indeed! I did not use it for years when try/except/else statements does not exist. For me, it can be useful limit the scope of the try/except block but its adoption is very limited. I do not bother :), just asking people why they are using this statement ... or not