哪个在结构上更好?
class Program
{
static void Main(string[] args)
{
try
{
using (Foo f = new Foo())
{
//some commands that potentially produce exceptions.
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
或者...
class Program
{
static void Main(string[] args)
{
using (Foo f = new Foo())
{
try
{
//some commands that potentially produce exceptions.
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
最佳答案
两者都可以,具体取决于您要在捕获中做什么。如果您需要在 catch 中使用 f
,那么它需要在 using 语句中。但是在您的示例中没有区别。
编辑:
正如在其他地方指出的那样,它还取决于您是试图仅捕获在 using 之后的 block 中生成的异常,还是在 using 语句中包含对象创建。如果它在 using 之后的 block 中,那么它就像我描述的那样。如果你想捕获 Foo f = new Foo()
产生的异常,那么你需要使用第一种方法。
关于c# - 在代码中使用 '"using"关键字时,我应该在哪里捕获异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3395518/