簡體   English   中英

處理錯誤捕獲的最佳方法

[英]Best way to handle error catching

我正在創建一個執行一些SQL Server配置的應用,這是更大系統的一部分

系統數據庫中有一個配置表,如下所示:

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
}

還是完全其他方式?

看第二個例子,如果這是您想要的結果,那么看起來您只需要替換

catch
{
     lblFeedback.Text = message;
}

在第一個例子中

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

從第二個例子。

如錯誤消息所述,您嘗試使用未分配的變量“ 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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM