2

Please see the code below:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            mymethod();
        }
        catch (Exception ex)//First catch
        {
            MessageBox.Show(ex.ToString());
        }
    }

    private void mymethod()
    {
        int a = 10;
        int b = 0;
        try
        {
            int c = a / b;
        }
        catch (Exception ex)//Second catch
        {
            MessageBox.Show(ex.ToString());
            //int c = a / b;
            throw new Exception(ex.ToString());
        }
    }
}

I want to force the first catch to execute after the second catch executes! How can I force the above to run and show the second catch error? I want to see the same ex.ToString() for both catch blocks.

Thanks in advance.

Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
SilverLight
  • 19,668
  • 65
  • 192
  • 300

1 Answers1

5

Instead of throwing a new exception, just rethrow the existing one:

private void mymethod()
{
    int a = 10;
    int b = 0;
    try
    {
        int c = a / b;
    }
    catch (Exception ex)//Second catch
    {
        MessageBox.Show(ex.ToString());
        //int c = a / b;
        throw; // change here
    }
}

See this post for details on how to properly rethrow an exception.

Update: Another, but slightly less preferred way to capture the mymethod exception and provide those details to the click handler would be to pass the exception along wrapped in a new one:

private void mymethod()
{
    int a = 10;
    int b = 0;
    try
    {
        int c = a / b;
    }
    catch (Exception ex)//Second catch
    {
        MessageBox.Show(ex.ToString());
        //int c = a / b;
        throw new Exception("mymethod exception", ex); // change here
    }
}

Again, the post I linked to has more detail.

Community
  • 1
  • 1
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194