Multiple try-catch or one?

前端 未结 11 1750

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: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
    }
    

提交回复
热议问题