【问题标题】:c++ winform error handlingc++ winform错误处理
【发布时间】:2013-04-03 08:48:56
【问题描述】:
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 的值之外它们都是相同的。我的问题是,如果我单击按钮,即使表单中不存在网页元素(“u”),如何让我的应用程序停止退出/出现错误。因为如果我单击它,即使表单尚未完全加载,我得到消息框说未处理的异常错误,我想将其更改为其他内容或只是忽略它并让我的应用程序再试一次。谢谢

【问题讨论】:

  • 您将不得不修复您的代码,它无法按设计工作。将您的代码移至 DocumentCompleted 事件的事件处理程序。

标签: winforms c++-cli


【解决方案1】:

对这种简单的检查使用异常处理是多余的。只需执行以下操作:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 嗨,谢谢你的回答,但是当我尝试这个时出现错误:“无法通过值或引用抛出或捕获托管对象”和“不能被捕获为析构函数和/或复制构造函数无法访问”
    • 您需要在 catch 子句中添加一个^catch (Exception^ ex)。见编辑。
    猜你喜欢
    • 2013-05-15
    • 1970-01-01
    • 2017-09-01
    • 2011-06-07
    • 2014-05-11
    • 2011-11-19
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多