Multiple try-catch or one?

前端 未结 11 1720

Normally, I\'d do this:

try
{
    code

    code that might throw an anticipated exception you want to handle

    code

    code that might throw an anticip         


        
相关标签:
11条回答
  • 2020-12-08 09:21

    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 ;)

    0 讨论(0)
  • 2020-12-08 09:26

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

    0 讨论(0)
  • 2020-12-08 09:29

    It depends. If you want to provide special handling for specific errors then use multiple catch blocks:

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

    If, however, the intent is to handle an exception and continue executing, place the code in separate try-catch blocks:

    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
    }
    
    0 讨论(0)
  • 2020-12-08 09:34

    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
       }
    
    0 讨论(0)
  • 2020-12-08 09:35

    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

    0 讨论(0)
  • 2020-12-08 09:37

    Neither, just use multiple catch blocks for specific exceptions (unless there is just a ton of code in the block and only a couple of lines may throw an exception.In that case I would go with the second method).

    0 讨论(0)
提交回复
热议问题