【问题标题】:Error not propagated错误未传播
【发布时间】:2016-01-29 09:52:54
【问题描述】:

这是我的动作处理程序中的代码:

    private async void startButton_Click(object sender, EventArgs e)
    {
        try
        {
            var expression = expressionTextBox.Text;
            var result = await Task.Run(() => Algebra.Divide(expression));
            resultTextBox.Text = result.Polynom.ToString();
        } catch (Exception ex)
        {
            Logger.Error(ex.Message);
            detailsTextbox.BackColor = Color.Red;
            detailsTextbox.AppendText("An error occurred! Please check if your expression is valid.");
        }
    }

而在Algebra.Divide 中,我只将抛出异常用于测试异常场景:

    public static DivisionResult Divide (string expression)
    {
            throw new Exception("Error occured");
    }

当我单击按钮时会发生以下情况:

为什么它不将异常传播到我有 try/catch 块的操作处理程序?我也尝试过不同步调用Algebra.Divide(),但这是同样的错误。

【问题讨论】:

  • 你有什么版本的C#? 5.0?

标签: c# .net winforms


【解决方案1】:

简单地说是因为您的调试器已启用。当您在没有调试器的情况下运行代码时,它将被您的 try catch 块捕获。当您看到异常时按 F5 时,您应该得到您想要的行为。在你的 catch 语句上放一个断点,你会看到你的程序将继续运行,并会转到 catch 语句。

您还可以关闭异常中断。你可以像这里描述的那样做:How to turn off "Break when exception is thrown" for custom exception types

【讨论】:

    【解决方案2】:

    您在任务中抛出异常。所以,异常是在不同的线程中抛出。试试看那个问题:What is the best way to catch exception in Task?

    【讨论】:

    • 已经是这样了。注意主题所有者的代码示例中的 await 关键字。编辑:但是 to 缺少方法上的 async 关键字
    • 不管我有什么版本。必须澄清他/她使用的是什么版本。但我假设他/她使用的是 c# 5 或更高版本,因为使用了 await 关键字并且没有编译错误?
    猜你喜欢
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    相关资源
    最近更新 更多