1

This is code in my action handler:

    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.");
        }
    }

And in Algebra.Divide I only put throwing exception for testing exception scenario:

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

And here is what happens when I click button: enter image description here

Why doesn't it propagate exception to action handler where I have try/catch block? I tried also without synchronous call to Algebra.Divide() but it is the same error.

Aleksa
  • 2,976
  • 4
  • 30
  • 49

2 Answers2

2

Simply said because your debugger is enabled. When you run the code without debugger it will be catched in your try catch block. You should get the behaviour you want when you press F5 when you see the exception. Put a breakpoint on your catch statement and you will see your program will continu running and will go to the catch statement.

You can also turn off the break on exception. You can do that like described here: How to turn off "Break when exception is thrown" for custom exception types

Community
  • 1
  • 1
Tom B.
  • 2,892
  • 3
  • 13
  • 34
0

You are throwing Exception in a Task. So, Exception is throwing in different thread. Try look at that question: What is the best way to catch exception in Task?

Community
  • 1
  • 1
Pavel Pája Halbich
  • 1,529
  • 2
  • 17
  • 22
  • This is already the case. Note the **await** keyword in the code example of the topic owner. Edit: however to is missing the **async** keyword on the method – Tom B. Jan 29 '16 at 10:00
  • Doesn't matter what version I have. To must clarify what version he/she is using. But I assume he/she is using c# 5 or higher since the await keyword is used and there is no compilation error? – Tom B. Jan 29 '16 at 10:03