Are nested Try/Catch blocks a bad idea?

后端 未结 2 2036
一生所求
一生所求 2020-12-03 00:42

Let\'s say we have a structure like so:

Try
  \' Outer try code, that can fail with more generic conditions, 
  \' that I know less about and might not be ab         


        
2条回答
  •  孤城傲影
    2020-12-03 01:05

    I actually don't think there's anything inherently wrong about nested Try/Catch blocks, except that they can be difficult to navigate and are likely a sign that you could do some refactoring (the inner Try/Catch into its own method, for example).

    But I do want to address this comment:

    ' Outer try code, that can fail with more generic conditions, 
    ' that I know less about and might not be able to handle
    

    If you don't know how to handle exceptions in a particular situation, trust me: don't catch them. Better to let your app crash (I mean, you know, log it; just don't swallow it) than to catch something you don't know how to recover from and then let your app continue merrily on its way in a corrupted state. Behavior will be unpredictable at best from that point on.

提交回复
热议问题