简体   繁体   English

C#“使用”语句并尝试/捕获

[英]C# “using” statement and try/catch

Ive been doing some research today on when an how to use the "using" statement to dispose of my sql objects. 我今天一直在研究如何使用“ using”语句处置我的sql对象。 However I'm still confused about when and how to catch unforseen errors. 但是,我仍然对何时以及如何捕获无法预料的错误感到困惑。 I have a simple method here and would appreciate any input on wheter its correct or I'm doing something wrong? 我这里有一个简单的方法,希望您输入正确的信息或者我做错了什么?

private BindingList<My_Object> Search(int ID)
{
   string strSelectStatement = 
     "SELECT 'coloumns' " +
     "FROM 'table' " +
     "WHERE ID = @ID;";

     DataTable dt = new DataTable();
     try
     {
        using (SqlConnection sqlConn = new SqlConnection(m_SQLConnectionString))
        {
          using (SqlCommand cmd = new SqlCommand(strSelectStatement, sqlConn))
          {
            cmd.Parameters.Add("@ID", SqlDbType.Int).Value = ID;
            using (SqlDataAdapter adpt = new SqlDataAdapter(cmd))
            {
               adpt.Fill(dt);
            }
          }
        }

        My_Object myObject;
        BindingList<My_Object> myObjectList = new BindingList<My_Object>();

        foreach (DataRow row in dt.Rows)
        {
          myObject = new My_Object();
          //Fill/set myObject properties and add to myObject list
        }

        return myObjectList;
     }
     catch (Exception)
     {
        //throw the the exception with its stack trace up to the main call
        throw;
     }
}

So what my catch here would do is catch an error if anything went wrong when running adapter.Fill, or while building myObject/list for example. 因此,在运行adapter.Fill或构建myObject / list时,如果发生任何错误,我的捕获将捕获错误。

Thanks 谢谢

Don't catch 'unforeseen' errors, since there's nothing you can do if truly unforeseen. 不要捕获“无法预料的”错误,因为如果真的无法预料,您将无能为力。

Unless of course you are wishing to handle these errors in some way, say, to log messages - but the system does that for you - then they are no longer 'unforeseen', since you're expecting them. 除非您当然希望以某种方式处理这些错误(例如,记录消息),但是系统会为您执行这些操作,否则它们就不再是“不可预见的”,因为您已在期待它们。

As for the code posted, there are problems. 至于张贴的代码,有问题。 Firstly, the try / catch could be said to be trying too much, and given that you have using s in there, that is pointless (if exceptions aren't going to be handled.) It also catches a generic exception, which is highly discouraged; 首先,可以说try / catch 尝试太多,并且考虑到您在其中using s,这是没有意义的(如果不会处理异常)。它还捕获了一个通用异常,这在很大程度上泄气; catch es should be formulated to filter those that you can handle, and in appropriate order. catch应制定适当的顺序,以过滤出您可以处理的catch To catch just to throw is also pointless. 仅仅throw也没有意义。

Don't catch exceptions if you can do nothing about it. 如果您对此无能为力,请不要捕获异常。 If you catch them is in order to clean up the unmanaged ressources or for logging purposes. 如果发现它们是为了清理非托管资源或用于日志记录目的。

You might have a look on MSDN "Best Practices for Handling Exceptions" http://msdn.microsoft.com/en-us/library/seyhszts.aspx 您可以看看MSDN“处理异常的最佳实践” http://msdn.microsoft.com/zh-cn/library/seyhszts.aspx

In C# . 在C#中。 The using statement defines the scope of an item to be disposed. using语句定义了要处置项目的范围。 This can be called for any object which implements the IDisposable interface. 可以为实现IDisposable接口的任何对象调用此方法。

http://msdn.microsoft.com/en-us/library/system.idisposable.aspx http://msdn.microsoft.com/en-us/library/system.idisposable.aspx

So if you had to not use using blocks you would call the dispose method on the class to release/clean up resources created by the object. 因此,如果您不必使用using块,则可以在类上调用dispose方法以释放/清理由对象创建的资源。

When calling a class that implements the IDisposable interface, the try/finally pattern make sure that unmanaged resources are disposed of even if an exception interrupts your application. 当调用实现IDisposable接口的类时,try / finally模式确保即使异常中断了您的应用程序,也处置了非托管资源。

If an exception is thrown in the case of a using statement the dispose will still be called. 如果在using语句中抛出异常,则将继续调用dispose。 You can also stack using statements 您还可以使用using语句进行堆栈

using (SqlConnection sqlConn = new SqlConnection(m_SQLConnectionString))
using (SqlCommand cmd = new SqlCommand(strSelectStatement, sqlConn))
          {
            cmd.Parameters.Add("@ID", SqlDbType.Int).Value = ID;
            using (SqlDataAdapter adpt = new SqlDataAdapter(cmd))
            {
               adpt.Fill(dt);
            }
          }

with regards to exception handling. 关于异常处理。 It is not wise to catch all exceptions try to catch the specific exceptions thrown by the class or method. 捕获所有异常尝试捕获类或方法引发的特定异常是不明智的。 You can view exception details on msdn so SQLConnection : http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open.aspx 您可以在msdn上查看异常详细信息,以便使用SQLConnection: http : //msdn.microsoft.com/zh-cn/library/system.data.sqlclient.sqlconnection.open.aspx

InvalidOperationException 出现InvalidOperationException
Cannot open a connection without specifying a data source or server. 如果不指定数据源或服务器,则无法打开连接。

or 要么

The connection is already open. 连接已打开。

SqlException SQLEXCEPTION
A connection-level error occurred while opening the connection. 打开连接时发生连接级错误。 If the Number property contains the value 18487 or 18488, this indicates that the specified password has expired or must be reset. 如果Number属性包含值18487或18488,则表明指定的密码已过期或必须重置。 See the ChangePassword method for more information. 有关更多信息,请参见ChangePassword方法。

So these are the exceptions you should cater for. 因此,这些是您应满足的例外情况。 Hope that helps! 希望有帮助!

You don't need the try..catch {throw}. 您不需要try..catch {throw}。 This is the same as not having a try..catch block at all. 这与根本没有try..catch块相同。

If you want to log the error of display a friendly message, then put the code in the catch { }. 如果要记录显示友好信息的错误,则将代码放在catch {}中。

The Dispose will still be called on the SqlConnection, even if the code crashes. 即使代码崩溃,仍将在SqlConnection上调用Dispose。

You can catch multiple exceptions at the end of your try statement. 您可以在try语句的末尾捕获多个异常。 This means you can catch each different type of error that could occur ie InvalidOperationException / SqlException. 这意味着您可以捕获可能发生的每种不同类型的错误,即InvalidOperationException / SqlException。 MSDN Explains here: MSDN在这里解释:

http://msdn.microsoft.com/en-us/library/ms173162(v=vs.80).aspx http://msdn.microsoft.com/en-us/library/ms173162(v=vs.80).aspx

Since you have enclosed your whole code in try/Catch it will catch all errors raised within try/catch code block. 由于您已将整个代码封装在try / Catch中,因此它将捕获try / catch代码块中引发的所有错误。 But don't follow this apprach only catch those errors specifically which you want to handle or log. 但是不要遵循这种方法,只能捕获您要处理或记录的那些错误。 this is recommended because catching error is an overhead. 建议这样做,因为捕获错误是一项开销。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM