gpt4 book ai didi

exception - 多次 try-catch 还是一次?

转载 作者:行者123 更新时间:2023-12-03 05:36:57 27 4
gpt4 key购买 nike

通常情况下,我会这样做:

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 评论的那样,它可以适用于任何异常处理语言,所以我让标签反射(reflect)了这一点。

最佳答案

这要看情况。如果您想为特定错误提供特殊处理,请使用多个 catch block :

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 block 中:

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
}

关于exception - 多次 try-catch 还是一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3239906/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com