多次尝试或一次?

Ste*_*eve 63 exception-handling

通常,我会这样做:

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 
{

}
Run Code Online (Sandbox Code Playgroud)

这样做有什么好处吗?

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
Run Code Online (Sandbox Code Playgroud)

更新:

我最初问这个问题w /引用C#,但正如A. Levy评论的那样,它可以应用于任何异常处理语言,所以我让标签反映了这一点.

Jam*_*Ide 77

这取决于.如果要为特定错误提供特殊处理,请使用多个catch块:

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

但是,如果意图是处理异常并继续执行,请将代码放在单独的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
}
Run Code Online (Sandbox Code Playgroud)

  • +1,在第一个示例中突出显示,确保常规异常处理程序在声明中的最后一个,以便您首先处理特定的,然后以通用方式处理控件之外的任何其他内容. (4认同)

Dar*_*rov 14

如果我可以选择第二个,我可能会把它分成两个函数.

  • +1:我完全同意,虽然我可能会把它写成"如果我可以选择第二个,我会......",因为我认为这是正确的事情,任何时候它都可能...... (4认同)

Ed *_* S. 11

也没有,只使用多个catch块来处理特定的异常(除非块中只有大量的代码,只有几行可能会抛出异常.在这种情况下,我会使用第二种方法).


zwo*_*wol 8

你正在考虑这个错误的方法.在catch块中你需要做什么?如果您可以通过运行相同的代码任何可能的异常中恢复,无论哪个操作引发了异常,那么使用一个catch块.如果您需要根据投掷的操作执行不同的清理操作,请使用多个catch块.

此外,如果你可以使用try/finally或RAII模式而不是try/catch,那么你应该.


EKS*_*EKS 5

我认为第二种方法更好,因为它可以让您更准确地捕获错误。

另外,如果您的应用程序出现某种问题并且崩溃了,那么将整个代码包装在一个大的 try/catch 块中也是不好的,但由于您捕获了一个大的通用执行,因此您实际上可以正确处理它的机会会较低。您应该在 try catch 中包含特定的部分,例如读取文件或获取用户输入。这样你就可以更好地处理异常