c# - try catch block 中的对象

标签 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
}

所以我的问题是:发生异常时,try块中的对象会发生什么?
如果发生异常,C#是否可以让我变得懒惰并销毁对象(销毁待处理的事务,意味着回滚)并关闭连接?

我来自C \ C++背景,因此为了安全起见,我正在做上述事情,并且如果下面发生异常,则不会以打开事务结束。

最佳答案

您应该处置/关闭连接和事务。

最好的方法是将创建内容包装在 using statement中。

Provides a convenient syntax that ensures the correct use of IDisposable objects.



本质上,using语句将对象的创建包装在 try{}finally{} 块中,以确保正确处理。
    using(var cmd = defs.prepquery(""))
    using(var trans = cmd.Connection.BeginTransaction())
    {

    }

关于c# - try catch block 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9671456/

相关文章:

c# - 使用 FTP 协议(protocol)列出包含大约 2,000,000 个文件的目录

c# - 如何使用新的 DI 通过 IWebJobsStartup 将 ILogger 注入(inject)到 Azure 函数中?

javascript - 无法在 Razor 的部分 View 中使用脚本渲染部分

C# 性能因内存而异

excel - 宏到自动排序表

sql - 错误显示时首先显示错误消息,然后返回(MS Sql Server)

java - 是否可以捕获除运行时异常之外的所有异常?

swift - do - try - catch 代码不尝试或捕获。只是做

javascript - 如何在 JavaScript 中捕获数组索引越界?

c++ - try-catch block 是否会降低性能