尝试捕获并清理

时间:2012-07-11 12:25:08

标签: c#

这是我的DAL,我即将尝试/捕获代码,因为这个概念不是我的成长,我有以下疑问。 实际执行某项操作的一次是 ExecuteSQL 方法。所以,我会有一次尝试/捕获。但是在 GetLinea UpdateLinea 中我还应该添加吗?我只能想到那里非常奇怪的错误。

此外,如果您对此代码中的清理有任何建议,我很乐意听到它。 感谢。

namespace DAL
{
    public class Connection
    {
        public string GetNewConnection(string server)
        {
            return ConfigurationManager.ConnectionStrings[server].ConnectionString;
        }

        public DataSet ExecuteSQL(string sp)
        {
            DataSet ds = new DataSet();
            string connectionString = GetNewConnection("BO");
            SqlConnection conn = new SqlConnection(connectionString);
            SqlCommand command = new SqlCommand(sp, conn);
            command.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(command);
            using (conn)
            {
                da.Fill(ds);
            }
            return ds;
        }
    }
    public class LineaDAL
    {
        Connection obj = new Connection();
        public DataSet GetLinea()
        {
            DataSet ds = new DataSet();
            string sp;
            sp = "sp1";
            ds = obj.ExecuteSQL(sp);
            return ds;
        }

        public bool UpdateLinea(string reclamo)
        {
            DataSet ds = new DataSet();
            string sp;
            sp = "sp2";
            ds = obj.ExecuteSQL(sp);
            return ExtensionMethods.IsEmpty(ds);
        }
    }

    public static class ExtensionMethods
    {
        public static bool IsEmpty(this DataSet ds)
        {
            return ds == null ||
              !(from DataTable t in ds.Tables where t.Rows.Count > 0 select t).Any();
        }
    }

}

4 个答案:

答案 0 :(得分:3)

与任何异常处理一样,它实际上取决于您将如何处理它。通常尝试使用/ catch作为一种方法来捕获可能的错误以防万一。但是,实际上你应该只有很少的尝试/捕获,除非你想要捕获一些特定的东西并正确处理它(通知用户该错误的自定义消息)。如果你没有与catch有任何意义,那么让它冒泡到顶级异常处理程序。这至少是我2美分

Here is a much more in depth article on exception handling

答案 1 :(得分:1)

通过数据库访问,尝试/ catch / finally总是一个好主意:

尝试执行数据库操作(选择,插入,更新,删除或删除)

捕获任何错误(数据库连接丢失,sql无效,......你永远不知道)

终于清理所有内容(必要时丢弃连接,......)

这不是因为你只能想出“奇怪的错误”,一切都会顺利进行。并且您的应用程序有责任处理错误,并告知用户出现了什么问题(即告诉用户检查他的网络连接)。

希望有所帮助:)

答案 2 :(得分:1)

好吧,GetLineaUpdateLinea考虑到执行SQL查询可以失败。

但是从他们那里抓住一个例外,根据问题的答案,你必须决定一下:该方法内部发生的异常是致命错误吗?如果是,请不要使用try/catch处理它并让它失败您的程序(致命错误)。否则在try/catch

中插入它们

清理一些使用finally块

try {
...
}
catch(Exception ex)
{
  ...
}
finally {

 .. cleanup...
}

保证执行(在大多数情况下)是否有异常。

答案 3 :(得分:1)

记录错误是个好主意。

类似的东西:

try
{
...
}
catch(Exception ex)
{
    Log(ex.Message);
    MessageBox.Show("Error Occured. Please try again later."); //General message to the user 
}
finally
{
    Cleanup... like Disposing objects (like com objects) if they need to be disposed.
}

您可以使用Log4Net之类的东西进行登录,但也可以建立自己的记录器。

如果您认为这段代码可能导致错误,那么使用try / catch 是一个很好的做法,即使您确定已经处理了可能导致它们的条件。在你的情况下,为什么不使用,只是为了确保如果发生异常,它就会被处理。