Winforms c++;winform错误处理

Winforms c++;winform错误处理,winforms,c++-cli,Winforms,C++ Cli,我有许多其他按钮调用函数navigate(),但我只发布一个,因为除了url的值之外,它们都是相同的。我的问题是,即使表单中不存在webpageelement(“u”),如果我单击按钮,如何使我的应用程序停止退出/出现错误。因为如果我点击它,即使表单尚未完全加载,我也会收到messagebox上说的未处理异常错误,我想将其更改为其他错误,或者忽略它,让我的应用程序再试一次。thx使用try和catch可以为您提供一些基本方法。。。比如说 private: System::Void link1_C

我有许多其他按钮调用函数navigate(),但我只发布一个,因为除了url的值之外,它们都是相同的。我的问题是,即使表单中不存在webpageelement(“u”),如果我单击按钮,如何使我的应用程序停止退出/出现错误。因为如果我点击它,即使表单尚未完全加载,我也会收到messagebox上说的未处理异常错误,我想将其更改为其他错误,或者忽略它,让我的应用程序再试一次。thx

使用
try
catch
可以为您提供一些基本方法。。。比如说

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");
             }
     }

对这种简单的检查使用异常处理是一种过分的做法。只需执行以下操作:

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
    }
}

您好,谢谢您的回答,但是当我尝试这样做时,我有一个错误:“无法通过值或引用抛出或捕获托管对象”和“由于析构函数和/或复制构造函数不可访问而无法捕获”您需要在catch子句中加上一个
^
catch(异常^ex)
。请参阅编辑。您必须修复代码,它无法按设计工作。将代码移动到DocumentCompleted事件的事件处理程序。
HtmlElement ele = this->webBrowser->Document->GetElementById("u");
if (ele != null)
  ele->SetAttribute("value", url);