【问题标题】:How to handle an exception without closing application? [closed]如何在不关闭应用程序的情况下处理异常? [关闭]
【发布时间】:2014-07-30 02:46:02
【问题描述】:

我有一个 try catch 用于通过 WPF C# 应用程序发送电子邮件,如下所示:

try { smtpmail.Send(message); }
            catch (Exception err) { throw new CustomException("Error contacting server.", err); }

但是,如果遇到此错误,我不希望应用程序停止运行/崩溃。相反,只需将错误更改为错误消息TextBox 我已在应用程序中设置...或与不使应用程序崩溃相关的内容,而是通知用户稍后再试(或者如果问题仍然存在:联系so-and - 所以)。

编辑: 预期:要记录错误,但用户会看到,

errorMsg.Text = "Error contacting server. Try again later, or if problem persists contact Billy Bob Boo";

我该如何实施?

更新:对于不清楚的问题表示歉意。基本上我需要关于如何记录我的错误但向用户显示友好错误消息的帮助......但我问得不好。使用提供的 cmets 和答案,我在下面进行了更多研究,回答了我自己的问题。感谢大家! :)

【问题讨论】:

  • 如果你要扔,你需要在某个地方接住。
  • 如果你不想抛出错误,为什么要捕获错误然后抛出另一个异常?
  • 可能会抛出异常(并且您的程序崩溃),因为您正在抛出异常。你抓住它,但重新抛出它。要么在链的更远位置捕获错误并记录它/显示错误消息(但不要使程序崩溃),要么在此处执行此操作。
  • @Savanna 我捕获并声明异常err,但不要在任何地方使用它。我不希望用户确切知道错误是什么,所以我抛出一个CustomException
  • 你卡在哪里了?你知道如何将文本放入文本框中吗?解决方案的哪一部分让您感到困惑?

标签: c# wpf exception-handling


【解决方案1】:

为什么你捕捉到异常然后又抛出它?这似乎不是很有效。

您可以使用消息框...

try { 
    smtpmail.Send(message); 
}catch (Exception err) { 
    MessageBox.Show(err.Message, "Exception", MessageBoxButton.OK, MessageBoxImage.Error);
}

编辑:您刚才说您不希望用户知道异常。好吧,那就把catch块留空吧:)

【讨论】:

  • just leave the catch block empty 这是个坏建议。至少应记录异常,还应显示错误消息(不一定显示详细信息)。
  • @tnw 我之所以这么说,是因为他说他不想在任何地方使用它,也不想让用户知道它。但你是对的,他至少应该把它记录到一个文件或其他东西中。
  • 是的,我至少想把它记录在某个地方。答案虽然有效,但我会对其进行一些调整,以便用户不会进入完成页面。 xD
【解决方案2】:

我是如何解决我的问题的:

bool success = false;
            try { 
                //try to send the message
                smtpmail.Send(message);
                success = true;//everything is good
            }
            catch (Exception err)
            {
                //error with sending the message
                errorMsg.Text = ("Unable to send mail at this time. Please try again later.");

                //log the error 
                errorLog.Log(err); //note errorLog is another method to log the error


                //other stuff relating to certain parts of the application visibility

            }
            finally
            {
                if (success)
                { 
                    //what to do if the email was successfully sent
                }
            }

【讨论】:

  • 为什么是成功标志?只需将这些操作放在smtpmail.Send() 之后。无论是否抛出异常,都应该使用 finally 块来执行代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-29
  • 1970-01-01
  • 2017-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多