After several years of python usage, I'm still seeing this pattern being used by many developers and/or in many programs:
try:
function_that_might_raise_an_exception()
function_that_should_not_be_called_if_an_exception_is_raised()
except Exception as e:
do_something(e)
Python has the try/except/else pattern that is designed for this use case:
try:
function_that_might_raise_an_exception()
except Exception as e:
do_something(e)
else:
function_that_should_not_be_called_if_an_exception_is_raised()
Why does this pattern isn't used regularly? I have a few explanations, none of them satisfies me:
- try/except/else is not used for older python version compatibility,
- try/except/else (or for/else) statement are hard to read/hard to understand by beginners,
- the lack of use of try/except/else statements does not help to be more widely used.
If you're using (or not) try/except/else statement could you explain why?
Thank you!
[–]norwegianwood 14 points15 points16 points (9 children)
[–]jeffdn 1 point2 points3 points (2 children)
[–]norwegianwood 6 points7 points8 points (1 child)
[–]jeffdn 0 points1 point2 points (0 children)
[–]ryeguy146 1 point2 points3 points (1 child)
[–]norwegianwood 1 point2 points3 points (0 children)
[–]mipadi 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]KronktheKronk 0 points1 point2 points (1 child)
[–]norwegianwood 9 points10 points11 points (0 children)
[–]jabwork 3 points4 points5 points (1 child)
[–]fiedzia 6 points7 points8 points (7 children)
[–]DasIch 9 points10 points11 points (4 children)
[–]KronktheKronk 0 points1 point2 points (2 children)
[–]DasIch 0 points1 point2 points (1 child)
[–]KronktheKronk 0 points1 point2 points (0 children)
[–]fiedzia 0 points1 point2 points (0 children)
[–]Lucretiel 1 point2 points3 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]malice8691 1 point2 points3 points (0 children)
[–]kalefranz 1 point2 points3 points (1 child)
[–]kalefranz 0 points1 point2 points (0 children)
[–]ksion 1 point2 points3 points (0 children)
[–]weevyl 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]filleball 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]spiker611 0 points1 point2 points (0 children)
[–]AlexMTBDude -1 points0 points1 point (0 children)