我知道这个问题已经被问过很多次了,但我还是不明白正确的顺序应该是什么。
如果你想在创建对象时捕获异常,你必须将 try 和 catch 放在 using 语句之外:
try { using... } catch (Exception e) { }
如果你想在创建对象后捕获异常,那么:
using(...) { try {...} catch (Exception e) {} }
但是如果你想在对象创建期间和之后都捕获怎么办?会不会是:
try { using(...) { try {...} catch (Exception e) {} } } catch (Exception e) { }
或者只使用 try、catch 和 finally 和 dispose 会更好吗?
最佳答案
using block更多的是关于处置而不是创造。如文档中所述,它是此代码的快捷方式:
{
Font font1 = new Font("Arial", 10.0f);
try
{
byte charset = font1.GdiCharSet;
}
finally
{
if (font1 != null)
((IDisposable)font1).Dispose();
}
}
这是一个 try-catch block 的定义
The try block contains the guarded code that may cause the exception. The block is executed until an exception is thrown or it is completed successfully.
因此,策略由您决定。这段代码:
try
{
using(Font font1 = new Font("Arial", 10.0f))
{
byte charset = font1.GdiCharSet;
}
}
将被翻译为:
try
{
Font font1 = new Font("Arial", 10.0f);
try
{
byte charset = font1.GdiCharSet;
}
finally
{
if (font1 != null)
((IDisposable)font1).Dispose();
}
}
如您所见,您正在捕获由构造函数、 block 以及 Dispose
引起的异常。
鉴于此:
using(Font font1 = new Font("Arial", 10.0f))
{
try
{
byte charset = font1.GdiCharSet;
}
}
将被翻译为:
Font font1 = new Font("Arial", 10.0f);
try
{
try //This is your try
{
byte charset = font1.GdiCharSet;
}
}
finally
{
if (font1 != null)
((IDisposable)font1).Dispose();
}
所以在这里您将捕获既不是构造函数也不是 Dispose 引起的异常。
关于C# - Try/Catch/Finally 和使用正确的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52008272/