处理错误捕获的最佳方法

时间:2017-11-23 15:34:08

标签: c# sql-server error-handling ado.net

我正在创建一个应用程序来执行一些SQL服务器配置,这是更大系统的一部分

系统数据库中有一个配置表,如下所示:

CREATE TABLE Config
(
    ConfigItem NVARCHAR(255) PRIMARY KEY NOT NULL,
    ConfigValue NVARCHAR(255) NOT NULL
)

INSERT INTO Config
VALUES
('LinkedServerName','MYLINKEDSERVER'),
('DatabaseName','APPLICATIONDATABASE')

我的应用是一个带有两个文本框和一个按钮的Windows窗体。表单还有一个最初为空白的标签,用于向用户显示错误消息。

在第一个文本框中,显示链接服务器名称的值,在第二个文本框中,显示数据库的值。两者都显示在表格载荷上。

单击“提交”按钮,将根据文本框中的内容在数据库中更新这两个值。

我有以下代码在表单加载时使用当前值填充两个文本框:

    private void Form1_Load(object sender, EventArgs e)
    {
        // populate the textboxes
        txtLinkedServer.Text = GetConfigValue("LinkedServerName");
        txtDatabase.Text = GetConfigValue("DatabaseName");
    }

    private string GetConfigValue(string ConfigItem)
    {
        // get the value for the given config item from the database
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            DataTable dt = new DataTable();
            SqlCommand com = new SqlCommand();
            com.CommandText = "SELECT ConfigValue FROM Config WHERE ConfigItem = @ConfigItem";
            com.Parameters.AddWithValue("ConfigItem", ConfigItem);
            com.Connection = conn;

            try
            {
                conn.Open();
                dt.Load(com.ExecuteReader());

                if (dt.Rows.Count == 0)
                {
                    return "Error retrieving " + ConfigItem + " name from config table";
                }
                else
                {
                    return dt.Rows[0]["ConfigValue"].ToString();
                }
            }
            catch
            {
                return "Error in GetConfigValueMethod when retrieving " + ConfigItem;
            }
            finally
            {
                conn.Close();
            }
        }
    }

如果检索配置数据有问题(由GetConfigValue中的catch块捕获),我希望标签显示从GetConfigValue返回的字符串。

最好/最好的方法是什么?我在想

private void Form1_Load(object sender, EventArgs e)
{
    string message;
    // populate the textboxes
    try
    {
         message = GetConfigValue("LinkedServerName");
         txtLinkedServer.Text = message
    }
    catch
    {
         lblFeedback.Text = message;
    }
    // do the same for the database here
}

但是,我不能这样做

  

使用未分配的本地变量'消息'

或者我最好更改GetConfigValue方法,以便它在catch块中抛出它自己的异常,而不是返回一个字符串并在Load方法中捕获它,如下所示;

private string GetConfigValue(string ConfigItem)    
{
    // get the value for the given config item from the database
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
             // same code here

        try
        {
            // same code here
        }
        catch
        {
            Throw new Exception ("Error in GetConfigValueMethod when retrieving " + ConfigItem);
        }
        finally
        {
            conn.Close();
        }
    }
}

private void Form1_Load(object sender, EventArgs e)
{
    // populate the textboxes
    try
    {
         txtLinkedServer.Text = GetConfigValue("LinkedServerName");

    }
    catch (Exception e)
    {
         lblFeedback.Text = e.Message;
    }
    // do the same for the database here
}

还是其他一些方式?

2 个答案:

答案 0 :(得分:0)

看看你的第二个例子,如果这是你想要的结果,那么看起来你只需要替换

catch
{
     lblFeedback.Text = message;
}

在你的第一个例子中

catch (Exception e)
{
     lblFeedback.Text = e.Message;
}

来自你的第二个例子。

答案 1 :(得分:0)

正如错误消息所示,您尝试使用未分配的变量'message',因此您收到了该错误。

试试这个:

private void Form1_Load(object sender, EventArgs e)
{
string message = String.Empty;
// populate the textboxes
try
{
     message = GetConfigValue("LinkedServerName");
     txtLinkedServer.Text = message
}
catch (Exception ex)
{
     if (!String.IsNullOrEmpty(message))
        lblFeedback.Text = message;
     else
        lblFeedback.Text = ex.Message;

}
// do the same for the database here

}

相关问题