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)
Dar*_*rov 14
如果我可以选择第二个,我可能会把它分成两个函数.
我认为第二种方法更好,因为它可以让您更准确地捕获错误。
另外,如果您的应用程序出现某种问题并且崩溃了,那么将整个代码包装在一个大的 try/catch 块中也是不好的,但由于您捕获了一个大的通用执行,因此您实际上可以正确处理它的机会会较低。您应该在 try catch 中包含特定的部分,例如读取文件或获取用户输入。这样你就可以更好地处理异常