Determine if executing in finally block due to exception being thrown

前端 未结 8 1263
遥遥无期
遥遥无期 2020-12-16 10:01

Is it possible to determine if code is currently executing in the context of a finally handler as a result of an exception being thrown? I\'m rather fond of usi

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-16 10:26

    I think the best way is to use write out try/catch/finally clause manually. Study an item from the first 'Effective c#" book. A good C# hacker should know exactly what using expands to. It has changed a bit since .Net 1.1 - you can now have several using one under another. So, use reflector, and study the un-sugared code.

    Then, when you write your own code - either use the using or write your own stuff. It is not terribly hard, and a good thing to know.

    You could get fancy with other tricks, but it feels too heavy, and even not efficient. Let me include a code sample.

    LAZY WAY:

    using (SqlConnection cn = new SqlConnection(connectionString))
    using (SqlCommand cm = new SqlCommand(commandString, cn))
    {
        cn.Open();
        cm.ExecuteNonQuery();
    }
    

    MANUAL WAY:

    bool sawMyEx = false;
    SqlConnection cn =  null;
    SqlCommand cm = null;
    
    try
    {
        cn = new SqlConnection(connectionString);
        cm = new SqlCommand(commandString, cn);
        cn.Open();
        cm.ExecuteNonQuery();
    }
    catch (MyException myEx)
    {
        sawMyEx = true; // I better not tell my wife.
        // Do some stuff here maybe?
    }
    finally
    {
        if (sawMyEx)
        {
            // Piss my pants.
        }
    
        if (null != cm);
        {
            cm.Dispose();
        }
        if (null != cn)
        {
            cn.Dispose();
        }
    }
    

提交回复
热议问题