嵌套的try / catch块 [英] Nested try/catch blocks

查看:81
本文介绍了嵌套的try / catch块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用嵌套的try / catch块有点犹豫。

让我想到的情况是以下情况。一些示例代码用于说明:

 SqlConnection conn = new SqlConnection(connectionString);< br />conn.Open();<br /> SqlTransaction trans = conn。 BeginTransaction();< br />< br />尝试< br /> {< br /> string query =query goes here;< br /> SqlCommand command = new SqlCommand( query,conn,trans);< br /> //添加参数< br />command.ExecuteNonQuery();<br />trans.Commit();<br />}< br /> catch< br /> {< br />trans.Rollback();<br />}< br />最后< br /> {< br /> if (conn!= null)< br /> {< br />conn.Close();<br />conn.Dispose();<br />}< br /> } 


这个块有1个try / catch块,但问题在于conn.Open();线。当出现网络错误时,conn.Open()将抛出异常。将conn.Open()放在try / catch块中会使现在驻留在catch / finally子句中的代码无效。

所以我可以使用2个连续的try / catch块或者nexted构造。你觉得怎么样?

解决方案

它不会使任何事情无效。你可以在第二个try / catch的开头放一个(if conn!= null)类型块,然后你的finally块就可以了。实际上,command.ExecuteNonQuery只会强制执行catch,最后,如果conn为null。我也不确定为什么conn不能在现有的try块中,只是在它之外声明trans,然后在里面开始它。搜索结果

I'm somewhat hesitating about using nested try/catch blocks.

The situation which makes me think about is the following situation. Some sample code to illustrate:

SqlConnection conn = new SqlConnection(connectionString);<br />conn.Open();<br />SqlTransaction trans = conn.BeginTransaction();<br /><br />try<br />{<br />string query = "query goes here";<br />SqlCommand command = new SqlCommand(query, conn, trans);<br />// add parameters<br />command.ExecuteNonQuery();<br />trans.Commit();<br />}<br />catch <br />{ <br />trans.Rollback();<br />}<br />finally<br />{<br />if(conn != null)<br />{<br />conn.Close();<br />conn.Dispose();<br />}<br />}


This block has 1 try/catch block but the problem resides in the "conn.Open();" line. When there is a network error the conn.Open() will throw an exception. Putting the conn.Open() in the try/catch block will invalidate the code which now resides in the catch/finally clauses.

So I can use 2 sequential try/catch blocks or a nexted construction. What do you people think?

解决方案

It won't invalidate anything. You can just put an (if conn != null) type block at the start of the second try/catch, and then your finally block will work fine. Indeed, command.ExecuteNonQuery would just force the catch and finally, if conn was null. I'm also not sure why conn couldn't be in the existing try block, just declare trans outside it, and begin it, inside.


这篇关于嵌套的try / catch块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆