C#“使用”声明和 try/catch
我今天一直在研究何时使用“using”语句来处理我的 sql 对象。 然而,我仍然对何时以及如何捕获不可预见的错误感到困惑。我这里有一个简单的方法,希望您能提供任何意见,无论它是正确的还是我做错了什么?
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;
}
}
因此,我在这里捕获的功能是,如果在运行adapter.Fill 或构建 myObject/list 时出现任何问题,则会捕获错误。
谢谢
Ive been doing some research today on when an how to use the "using" statement to dispose of my sql objects.
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.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在 C# 中。 using 语句定义了要处理的项目的范围。任何实现 IDisposable 接口的对象都可以调用此方法。
http://msdn.microsoft.com/en-us/library/system .idisposable.aspx
因此,如果您必须不使用 using 块,您将调用类上的 dispose 方法来释放/清理对象创建的资源。
当调用实现 IDisposable 接口的类时,try/finally 模式可确保即使异常中断应用程序也会释放非托管资源。
如果在 using 语句的情况下引发异常,则仍会调用 dispose。您还可以堆叠
有关异常处理的 using 语句。捕获所有异常尝试捕获类或方法抛出的特定异常是不明智的。您可以在 msdn 上查看异常详细信息,因此 SQLConnection : http ://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open.aspx
InvalidOperationException
如果不指定数据源或服务器,则无法打开连接。
或
连接已打开。
SQL异常
打开连接时发生连接级错误。如果 Number 属性包含值 18487 或 18488,则表示指定的密码已过期或必须重置。有关详细信息,请参阅 ChangePassword 方法。
因此,这些是您应该考虑的例外情况。希望有帮助!
In C# . The using statement defines the scope of an item to be disposed. This can be called for any object which implements the IDisposable interface.
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.
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.
If an exception is thrown in the case of a using statement the dispose will still be called. You can also stack using statements
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
InvalidOperationException
Cannot open a connection without specifying a data source or server.
or
The connection is already open.
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. See the ChangePassword method for more information.
So these are the exceptions you should cater for. Hope that helps!
不要发现“不可预见”的错误,因为如果确实不可预见,您将无能为力。
当然,除非您希望以某种方式处理这些错误,例如记录消息 - 但系统会为您做到这一点 - 那么它们不再是“不可预见的”,因为您正在期待它们。
至于发布的代码,有问题。首先,
try / catch
可以说是尝试太多,并且考虑到其中有using
,这是毫无意义的(如果不打算处理异常。)它还会捕获通用异常,但强烈建议不要这样做;catch
应该制定为过滤那些您可以处理的内容,并按适当的顺序。仅仅捕获抛出
也是毫无意义的。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 haveusing
s in there, that is pointless (if exceptions aren't going to be handled.) It also catches a generic exception, which is highly discouraged;catch
es should be formulated to filter those that you can handle, and in appropriate order. To catch just tothrow
is also pointless.如果您无能为力,请不要捕获异常。如果您捕获它们是为了清理非托管资源或用于日志记录目的。
您可以查看 MSDN“处理异常的最佳实践”http://msdn .microsoft.com/en-us/library/seyhszts.aspx
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
您不需要 try..catch {throw}。这与根本没有 try..catch 块相同。
如果要记录显示友好消息的错误,请将代码放在 catch { } 中。
即使代码崩溃,仍将在 SqlConnection 上调用 Dispose。
You don't need the try..catch {throw}. This is the same as not having a try..catch block at all.
If you want to log the error of display a friendly message, then put the code in the catch { }.
The Dispose will still be called on the SqlConnection, even if the code crashes.
您可以在 try 语句末尾捕获多个异常。这意味着您可以捕获可能发生的每种不同类型的错误,即 InvalidOperationException / SqlException。 MSDN 解释如下:
http://msdn.microsoft。 com/en-us/library/ms173162(v=vs.80).aspx
You can catch multiple exceptions at the end of your try statement. This means you can catch each different type of error that could occur i.e. InvalidOperationException / SqlException. MSDN Explains here:
http://msdn.microsoft.com/en-us/library/ms173162(v=vs.80).aspx
由于您已将整个代码包含在 try/Catch 中,因此它将捕获 try/catch 代码块中引发的所有错误。
但不要遵循这种方法,只捕获那些您想要处理或记录的错误。
推荐这样做,因为捕获错误是一种开销。
Since you have enclosed your whole code in try/Catch it will catch all errors raised within try/catch code block.
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.