shn*_*hnk 3 c# resources dispose using try-catch
我知道这个问题已被问过很多次但我仍然不明白应该是什么样的顺序.
如果要在对象创建中捕获异常,则必须将try和catch放在using语句之外:
try { using... } catch (Exception e) { }
Run Code Online (Sandbox Code Playgroud)
如果你想在创建对象后捕获异常,那么:
using(...) { try {...} catch (Exception e) {} }
Run Code Online (Sandbox Code Playgroud)
但是如果你想在对象创建期间和之后捕获它们呢?可不可能是:
try { using(...) { try {...} catch (Exception e) {} } } catch (Exception e) { }
Run Code Online (Sandbox Code Playgroud)
或者最好只使用try,catch,最后使用dispose?
在使用块更多的是关于出售比创作.如文档中所述,它是此代码的快捷方式:
{
Font font1 = new Font("Arial", 10.0f);
try
{
byte charset = font1.GdiCharSet;
}
finally
{
if (font1 != null)
((IDisposable)font1).Dispose();
}
}
Run Code Online (Sandbox Code Playgroud)
这是try-catch块的定义
try块包含可能导致异常的保护代码.执行该块直到抛出异常或成功完成.
所以,从那时起,战略取决于你.这段代码:
try
{
using(Font font1 = new Font("Arial", 10.0f))
{
byte charset = font1.GdiCharSet;
}
}
Run Code Online (Sandbox Code Playgroud)
将被翻译为:
try
{
Font font1 = new Font("Arial", 10.0f);
try
{
byte charset = font1.GdiCharSet;
}
finally
{
if (font1 != null)
((IDisposable)font1).Dispose();
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,您正在捕获构造函数,块以及Dispose.
鉴于此:
using(Font font1 = new Font("Arial", 10.0f))
{
try
{
byte charset = font1.GdiCharSet;
}
}
Run Code Online (Sandbox Code Playgroud)
将被翻译为:
Font font1 = new Font("Arial", 10.0f);
try
{
try //This is your try
{
byte charset = font1.GdiCharSet;
}
}
finally
{
if (font1 != null)
((IDisposable)font1).Dispose();
}
Run Code Online (Sandbox Code Playgroud)
所以在这里你将捕获异常因为构造函数和Dispose.