try catch块中的对象

Ler*_*tai 1 c# error-handling try-catch

拿这个代码示例:

string status = "ok";
SqlCommand cmd=null;
SqlTransaction trans=null;
try
{
    cmd = defs.prepquery("");
    trans = cmd.Connection.BeginTransaction();
    cmd.Transaction = trans;

}
catch (Exception ex)
{
    status = defs.logerror("initalizing sql transaction:" + ex.ToString());
    return status;
}

try
{
    if (oper == "submit")
    {
        cmd.CommandText = "update DCM_Mapping_Sessions set StatusID=2 " + 
            "where MappingSessionID=" + mpsid + "";
        cmd.ExecuteNonQuery();
    }
    else if (oper == "delete")
    {
        // .......etc etc 
    }
    catch(Exception ex2)
    {
        //rollback , close the connection
       // handle the ex 
    }

    // if everything is ok , comit the transaction and close the connection
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:当发生异常时,try块中的对象会发生什么?C#是否允许我延迟并销毁对象(销毁待处理的事务意味着回滚)并在发生异常时关闭连接?

我来自C\C++背景,所以我正在做我上面的事情是安全的,如果在下面某处发生异常,则不会以事务打开结束.

Mar*_*ngs 5

看看try-finally.

它完全符合您的要求.

所以你的代码看起来像:

try
{
   //try something
}
catch(Exception ex2)
{
   // handle the ex 
}
finally
{
    //rollback , close the connection
}
Run Code Online (Sandbox Code Playgroud)