code

여러 개의 try-catch 또는 하나?

codestyles 2020. 12. 4. 08:15
반응형

여러 개의 try-catch 또는 하나?


일반적으로 다음을 수행합니다.

try
{
    code

    code that might throw an anticipated exception you want to handle

    code

    code that might throw an anticipated exception you want to handle

    code
}
catch 
{

}

이렇게하면 어떤 이점이 있습니까?

code

try
{
    code that might throw an anticipated exception you want to handle
}
catch
{
}

code

try
{
    code that might throw an anticipated exception you want to handle
}
catch
{
}

code

최신 정보:

나는 원래 C #을 참조하여이 질문을했지만 A. Levy가 언급했듯이 모든 예외 처리 언어에 적용 할 수 있으므로 태그에이를 반영하도록 만들었습니다.


때에 따라 다르지. 특정 오류에 대한 특수 처리를 제공하려면 여러 catch 블록을 사용하십시오.

try
{ 
    // code that throws an exception
    // this line won't execute
}
catch (StackOverflowException ex)
{
    // special handling for StackOverflowException 
}
catch (Exception ex)
{
   // all others
}

그러나 의도가 예외를 처리하고 계속 실행하려는 경우 코드를 별도의 try-catch 블록에 배치합니다.

try
{ 
    // code that throws an exception

}
catch (Exception ex)
{
   // handle
}

try
{ 
    // this code will execute unless the previous catch block 
    // throws an exception (re-throw or new exception) 
}
catch (Exception ex)
{
   // handle
}

두 번째를 선택할 수 있다면 아마도 이것을 두 가지 기능으로 분리 할 것입니다.


둘 다 특정 예외에 대해 여러 catch 블록을 사용하십시오 (블록에 코드가 많고 몇 줄만 예외를 throw 할 수있는 경우가 아니면 두 번째 방법을 사용합니다).


You're thinking about this the wrong way. What do you need to do in your catch blocks? If you would recover from any of the possible exceptions by running the same code, no matter which operation threw the exception, then use one catch block. If you need to do different clean-up operations depending on which operation threw, then use multiple catch blocks.

Also, if you can use try/finally or the RAII pattern instead of try/catch, then you should.


Second method is better in my opinion because it allows you to trap errors with more accuracy.

Also wrapping your entire code inside one big try/catch block is bad, if your app has some sort of problem and it crashes but since you trapped a big generic execption the chance that you can actualy handle it correctly is lower. You should have spesfic parts inside try catch, like if your reading a file or taking user input. That way you can better handle that exeception


I prefer the second method - it makes debugging easier, error handling more accurate and also feeds nicely into your unit testing nicely too.


I would go for the 2nd option, but whenever I see this code pattern my first feeling is to think about splitting it into multiple functions/methods. Obviously whether to do so depends on what the code is doing ;)


It depends on the nature of the type of errors happen in your code.

  1. If the handling of those errors you are going to do is same go for single try ... catch for that group of code. Else it will be too tedious.

  2. If the errors required different handling, separate it because you have to.

DO NOT APPLY A SINGLE METHOD FOR ALL CASES. PROGRAMMING MOST OF THE TIME IS CONTEXT SPECIFIC :)

You need to reach a balance of "GOOD/COMPLEX" and "BAD/SIMPLE". The more you code, you will be less stuck in this kind of dilemma :)

Happy programming!


Second method. Keeping the code that might throw an exception separate from other code - keeps the section smaller and easier to manage instead of wrapping all code, even that which will not throw exceptions.


There are time we want to show specific error to user.

try{
   try{
      ... send message
   }
   catch(exception e){
    ...log error
    ...rethrow  send related error/show custom error
   }
   try{
       ...try to receive response
   }
   catch(exception e){
       ...show receive related error
   }
   //finally close the connection
   }finally{
        ...close connection
   }

2nd way but ideally use code guards - try/catch is costly

참고URL : https://stackoverflow.com/questions/3239906/multiple-try-catch-or-one

반응형