gpt4 book ai didi

c# - 处理来自另一个函数的异常

转载 作者:太空宇宙 更新时间:2023-11-03 19:10:30 25 4
gpt4 key购买 nike

我想生成一个打开 SQL 连接的方法:

public SqlConnection openConnection (string connString)
{
using (SqlConnection conn = new SqlConnection(connString))
{
try
{
conn.Open();
}
catch (Exception)
{
OrdersFaultException connEx = new OrdersDBInternalFaultException();
throw new FaultException<OrdersFaultException>(connEx);
return null;
}
return conn;
}
}

我想知道上面的代码是否正确?或者我应该在 openConnection 中抛出异常并在调用 openConnection 的函数中处理异常?

最佳答案

你不能在这里使用using:没有人想要一个disposed连接。所以您可以模拟使用:

public SqlConnection openConnection (string connString) {
SqlConnection conn = null;

try {
conn = new SqlConnection(connString));

return conn;
}
catch (Exception e) { // <- Probably, you should catch more specific exception, e.g. DataException
// This "if" (that's a part of typical using emulation scheme) is redundant
// you may safely remove it unless there's no addition code in the "try"
// see Todd Bowles comments
if (!Object.ReferenceEquals(null, conn))
conn.Dispose();

// Do not forget to pass the reason (intitial exception e)
// when throwing your own one
throw new OrdersDBInternalFaultException(e);
}
}

关于c# - 处理来自另一个函数的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20968937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com