是一个“ok”代码吗?
try
{ /*stuff*/ }
catch (Exception e)
{ /*stuff*/ }
finally
{
try
{ /*stuff*/ }
catch { /*empty*/ }
}
我需要在finally中执行复杂的操作,因为它连接到DB
,它可能会崩溃 这对我来说很奇怪,所以。这是正确的方法吗?答案 0 :(得分:3)
这实际上取决于你在做什么,但就个人而言,如果它真的是在另一个尝试捕获并在操作之后完成,我不会将它嵌套在最终,只是将其视为另一个尝试捕获。这将消除其中的一些“奇怪”。
答案 1 :(得分:1)
嵌套的try / catch块并不理想,但在某些情况下是必要的。只需确保正确处理任何错误。
答案 2 :(得分:1)
从根本上说,你会这样做:
try
{
/* stuff */
}
catch
{
/* stuff */
}
finally
{
DoStuff();
}
void DoStuff()
{
try
{
/* stuff */
}
catch
{
/* stuff */
}
}
答案 3 :(得分:0)
是。 finally
中的例外情况会隐藏原始异常。这与推荐not to use using in WCF while creating proxies
类似 - 尽管这本身就是一个不同的讨论。
这将输出B而不是A:
static void Main(string[] args)
{
try
{
try
{
throw new ApplicationException("A");
}
finally
{
throw new ApplicationException("B");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.Read();
}
答案 4 :(得分:0)
是。通常在另一个异常处于活动状态时抛出异常将导致第一个异常被第二个(稍后的)异常替换。
以下是一些说明会发生什么的代码:
public static void Main(string[] args)
{
try
{
try
{
throw new Exception("first exception");
}
finally
{
//try
{
throw new Exception("second exception");
}
//catch (Exception)
{
//throw;
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}