C# - Try/Catch/Finally 和使用正确的顺序

标签 c# resources try-catch dispose using

我知道这个问题已经被问过很多次了,但我还是不明白正确的顺序应该是什么。

如果你想在创建对象时捕获异常,你必须将 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/

相关文章:

c# - 全局异常处理 VS Try catch everywhere

c# - Entity Framework IdentityUser覆盖用户名不会保存在数据库中

javascript - 获取调用某个函数的脚本标签

php - 警告 : mysql_query(): 7 is not a valid MySQL-Link resource

c++ - 在运行时调用处理 constexpr。 C++

python - 为什么我的 Python 异常没有被重新引发?

c# - 方法或操作未实现 : Reset all sessions in my application

c# - 使用linq计算平均值而不分组

c# - 我如何保证 T 是一个类?

ruby - Middleman 博客 - 在哪里可以看到我可以在 config.rb 中设置的所有选项的列表?