Thanks for the info. I started learning Python and found this a good source of tips for proper error handling. I have a question:
def f2(x):
a = do_something(x)
try:
b = do_something_else(a)
except SomeException as err:
log_exception(err)
return None
else:
c = lastly_do(b)
log_or_whatever(c)
return c
Why do I need the else? Can I simply write it like this?
def f2(x):
a = do_something(x)
try:
b = do_something_else(a)
except SomeException as err:
log_exception(err)
return None
c = lastly_do(b)
log_or_whatever(c)
return c
technically you don't, in this case, because of the return. but if you don't have a return you still need the else, and i'd argue it's clearer/more informative either way.
yeah, depending on what you're trying to do—if everything's decoupled and bar doesn't depend on the success of foo, then this approach is the way to go
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Thanks for the info. I started learning Python and found this a good source of tips for proper error handling. I have a question:
Why do I need the else? Can I simply write it like this?
technically you don't, in this case, because of the
return
. but if you don't have areturn
you still need theelse
, and i'd argue it's clearer/more informative either way.So I will end up having nested try? As in
?
potentially! but like i said, it might be worth refactoring those cases into separate functions
So
Am I getting there?
yeah, depending on what you're trying to do—if everything's decoupled and
bar
doesn't depend on the success offoo
, then this approach is the way to go