Program Tip

중첩 된 Try / Catch 블록이 나쁜 생각입니까?

programtip 2020. 10. 19. 12:34
반응형

중첩 된 Try / Catch 블록이 나쁜 생각입니까?


다음과 같은 구조가 있다고 가정 해 보겠습니다.

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

  Try
    ' Inner try code, that can fail with more specific conditions,
    ' that I probably know more about, and are likely to handle appropriately
  Catch innerEx as Exception
    ' Handle the inner exception
  End Try

Catch outerEx as Exception
  ' Handle outer exception
End Try

Try이와 같은 중첩 블록이 권장되지 않는다는 의견을 봤지만 구체적인 이유를 찾을 수 없었습니다.

이것은 잘못된 코드입니까? 그렇다면 그 이유는 무엇입니까?


예를 들어 예외를 처리하고 나머지 컬렉션을 계속 처리하려는 경우 전체 메서드에 대해 하나의 try / catch를 사용하고 루프 내부에 다른 하나를 시도하는 것과 같은 특정 상황이 있습니다.

실제로 그렇게하는 유일한 이유는 스택을 풀고 컨텍스트를 잃는 대신 오류가 발생한 비트를 건너 뛰고 계속 진행하려는 경우입니다. 편집기에서 여러 파일을 여는 것이 한 가지 예입니다.

즉, 예외는 (이름에서 알 수 있듯이) 예외적이어야합니다. 프로그램은이를 처리해야하지만 정상적인 실행 흐름의 일부로이를 피해야합니다. 대부분의 언어 에서 계산 비용이 많이 듭니다 (Python은 주목할만한 예외 중 하나입니다).

유용한 다른 기술 중 하나는 특정 예외 유형을 포착하는 것입니다.

Try
    'Some code to read from a file

Catch ex as IOException
    'Handle file access issues (possibly silently depending on usage)
Catch ex as Exception
    ' Handle all other exceptions.
    ' If you've got a handler further up, just omit this Catch and let the 
    ' exception propagate
    Throw
End Try

또한 오류 처리 루틴에서 중첩 된 try / catches를 사용합니다.

    Try
        Dim Message = String.Format("...", )
        Try
            'Log to database
        Catch ex As Exception
            'Do nothing
        End Try

        Try
            'Log to file
        Catch ex As Exception
            'Do nothing
        End Try
    Catch ex As Exception
        'Give up and go home
    End Try

나는 실제로 중첩 Try/ Catch블록 에 대해 본질적으로 잘못된 것이 없다고 생각하지만 , 탐색하기 어려울 수 있고 리팩토링 (예 : 내부 Try/ Catch자체 방법)을 수행 할 수 있다는 신호일 가능성이 있습니다 .

그러나 나는이 코멘트를 다루고 싶다.

' 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.

참고URL : https://stackoverflow.com/questions/4799758/are-nested-try-catch-blocks-a-bad-idea

반응형