如何在不关闭应用程序的情况下处理异常

本文关键字:情况下 处理 异常 应用程序 | 更新日期: 2023-09-27 18:07:35

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

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

然而,我不希望应用程序停止运行/崩溃,如果这个错误被击中。相反,只需将错误更改为我在应用程序中设置的错误消息TextBox…或者与不使应用程序崩溃有关的内容,而是通知用户稍后再试(或者如果问题仍然存在:联系某某)。

编辑:期望:错误要被记录,但是用户看到这个,

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

我如何去实现这个?

更新:为不清楚的问题道歉。基本上,我需要帮助如何去记录我的错误,但显示一个友好的错误信息给用户…但我问得不好。使用评论和提供的答案,我研究了更多,回答了我自己的问题。谢谢,大家好!:)

如何在不关闭应用程序的情况下处理异常

为什么捕获异常然后再次抛出它?这似乎不是很有效。

你可以使用一个消息框…

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

编辑:你刚刚说你不想让用户知道异常。那么,让catch块为空:)

如何着手解决我的问题:

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