内部尝试/捕获(第二次尝试/捕获在一个方法内)

时间:2012-10-13 17:10:35

标签: c# exception-handling try-catch

请参阅以下代码:

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());
        }
    }
}

我希望在第二个catch执行后强制执行第一个catch!如何强制执行上述操作并显示第二个catch错误? 我希望两个ex.ToString()块看到相同的catch

提前致谢。

1 个答案:

答案 0 :(得分:5)

不要抛出新的异常,只需重新抛出现有的异常:

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有关如何正确重新抛出异常的详细信息。

更新:捕获mymethod异常并将这些详细信息提供给点击处理程序的另一种但不太优选的方法是将新异常传递给新的<:1 < / p>

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

同样,我链接的帖子有更详细的内容。