Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad nesting try/catch statements?

My case right now:

try:
  try:
    condition
  catch

  try:
    condition
  catch

catch
 major failure

Is it bad to have the code like that? Does it clutter too much, or what are the implications of something like that?

like image 866
Jorge Guberte Avatar asked May 02 '11 07:05

Jorge Guberte


2 Answers

No, that's somewhat common (except the keyword is except rather than catch). It depends on what you need to do and the design.

What IS bad, that I see too much of, is catching top-level Exception class, rather than something more specific (e.g. KeyError). Or raising the same.

like image 114
Keith Avatar answered Sep 29 '22 06:09

Keith


I wouldn't just cut a verdict and claim "it's bad", because sometimes you may need it. Python sometimes deliberately throws exceptions instead of letting you ask (does this ...?) [the EAFP motto] and in some cases nesting of try/catch is useful - when this makes sense with the logical flow of the code.

But my guess is that most times you don't. So a better question in your case would be to present a specific use case where you think you need such code.

like image 31
Eli Bendersky Avatar answered Sep 29 '22 08:09

Eli Bendersky