如果未在Try Catch C#中捕获异常,则显示另一条消息

时间:2018-06-12 14:27:04

标签: c#

我正在尝试让它显示另一条消息,只有在使用Try Catch时没有捕获到Exception。现在它将显示一个异常,然后我的消息显示。所以我只想问一些关于如何做到这一点的技巧。

这是我的代码。

try
        {


        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            MessageBox.Show("Solution Downloaded in C:/dwnload/working");
        }

3 个答案:

答案 0 :(得分:4)

您应该在可以在try语句中抛出异常的代码之后执行此操作。

try
{
    // do operation that could throw exception
    // display message
}
catch (Exception e)
{
    // catch code
}
finally
{
    // code to run at the end regardless of success/failure
}

答案 1 :(得分:4)

    try
    {
         // Do Work

         // when we get here: success! Without errors!
         MessageBox.Show("Solution Downloaded in C:/dwnload/working");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

答案 2 :(得分:2)

简单地将消息重构为变量。在try块的末尾分配成功消息。

在catch块中,分配错误消息。

然后根据您的喜好在finally块或之后显示MessageBox。

    string message;
    try
    {

         // at the end of try block
         message = "Solution Downloaded in C:/dwnload/working);
    }
    catch (Exception ex)
    {
         message = ex.Message;
    }
    finally
    {
        // in general, keep the finally code as the minimum needed for sanity cleanup. 
    }

    // If you rethrow your exception, and still want to show the message box, then might have a reason for wanting this instruction back inside the finally block. 
    MessageBox.Show(message);