c ++ winform错误处理

时间:2013-04-03 08:48:56

标签: winforms c++-cli

private: System::Void link1_Click(System::Object^  sender, System::EventArgs^  e) 
     {
        navigate(url1);
     }


private: System::Void navigate(System::String^ url)
     {
             for each ( System::Windows::Forms::HtmlElement^ webpageelement in webBrowser->Document->All )
             {
                 if (webpageelement->GetAttribute("u"))
                    this->webBrowser->Document->GetElementById("u")->SetAttribute("value", url);
             }

             for each ( System::Windows::Forms::HtmlElement^ webpageelement in webBrowser->Document->All )
             {
                 if (webpageelement->GetAttribute("value") == "Go")
                     webpageelement->InvokeMember("click");
             }
     }

我有许多其他按钮调用函数navigate()但我只发布一个因为它们都是相同的,除了url的值。我的问题是,即使表格中没有网页元素(“你”),如果单击按钮,如何使我的应用程序停止退出/出错?因为如果我点击它即使表单尚未完全加载我得到messagebox说未处理的异常错误,我想将其更改为其他东西或只是忽略它,让我的应用程序再试一次。 THX

2 个答案:

答案 0 :(得分:1)

对这种简单的检查使用异常处理是一种过度杀伤力。只需执行以下操作:

HtmlElement ele = this->webBrowser->Document->GetElementById("u");
if (ele != null)
  ele->SetAttribute("value", url);

答案 1 :(得分:0)

使用trycatch可以为您提供一些基本方法......例如

for each ( System::Windows::Forms::HtmlElement^ webpageelement in webBrowser->Document->All )
{
    try 
    {
        if (webpageelement->GetAttribute("u"))
        this->webBrowser->Document->GetElementById("u")->SetAttribute("value", url);
    }
    catch (Exception^ ex)
    {
        // Do something here, can be blank...
        // This will try the above code, if it doesn't work it will continue without any error popup
    }
}