1. 多个函数嵌套调用,只需要在最外层使用Try ... Catch ... Finally
public void BtnMultiNestClick(object sender, EventArgs e)
{
try
{
FisrtFunc();
}
catch(System.Exception ex)
{
richTextBox1.AppendText("Exception -> " + ex.Message + Environment.NewLine);
}
}
public void FisrtFunc()
{
richTextBox1.AppendText("FisrtFunc is run " + Environment.NewLine);
SecondFunc();
}
public void SecondFunc()
{
richTextBox1.AppendText("SecondFunc is run " + Environment.NewLine);
ThirdFunc();
}
public void ThirdFunc()
{
richTextBox1.AppendText("ThirdFunc is run " + Environment.NewLine);
throw new System.NotImplementedException("ThirdFunc");
}
2. Try ... Catch ... Finally 在Try块中有Retrun,执行到Return,然后跳转到Finally,接着退出
public void BtnTryReturnCatchFinally_Click(object sender, EventArgs e)
{
try
{
richTextBox1.AppendText("TryReturnCatchFinally -> Try" + Environment.NewLine);
return;
richTextBox1.AppendText("TryReturnCatchFinally -> Return" + Environment.NewLine);
}
catch
{
richTextBox1.AppendText("TryReturnCatchFinally -> Catch" + Environment.NewLine);
}
finally
{
richTextBox1.AppendText("TryReturnCatchFinally -> Finally" + Environment.NewLine);
}
richTextBox1.AppendText("TryReturnCatchFinally -> Outer" + Environment.NewLine);
}
3. Try ... Catch ... Finally 在Catch块中有Retrun,执行到Return,然后跳转到Finally,接着退出
public void BtnTryCatchReturnFinallyClick(object sender, EventArgs e)
{
try
{
richTextBox1.AppendText("TryCatchReturnFinally -> Try" + Environment.NewLine);
throw new System.Exception();
}
catch
{
richTextBox1.AppendText("TryCatchReturnFinally -> Catch" + Environment.NewLine);
return;
richTextBox1.AppendText("TryCatchReturnFinally -> Return" + Environment.NewLine);
}
finally
{
richTextBox1.AppendText("TryCatchReturnFinally -> Finally" + Environment.NewLine);
}
richTextBox1.AppendText("TryCatchReturnFinally -> Outer" + Environment.NewLine);
}
4. Try ... Catch ... Finally 在Finally块中有Retrun,编译不通过,报错:控制不能离开 finally 子句主体 (CS0157)
5. Try ... Catch在Try块中有Retrun,执行到Return,然后退出
public void BrnTryReturnCatchClick(object sender, EventArgs e)
{
try
{
richTextBox1.AppendText("TryReturnCatch -> Try" + Environment.NewLine);
return;
richTextBox1.AppendText("TryReturnCatch -> Return" + Environment.NewLine);
}
catch
{
richTextBox1.AppendText("TryReturnCatch -> Catch" + Environment.NewLine);
}
richTextBox1.AppendText("TryReturnCatch -> Outer" + Environment.NewLine);
}
6. Try ... Catch在Catch块中有Retrun,执行到Return,然后退出
public void BtnTryCatchReturnClick(object sender, EventArgs e)
{
try
{
richTextBox1.AppendText("TryCatchReturn -> Try" + Environment.NewLine);
throw new System.Exception();
}
catch
{
richTextBox1.AppendText("TryCatchReturn -> Catch" + Environment.NewLine);
return;
richTextBox1.AppendText("TryCatchReturn -> Return" + Environment.NewLine);
}
richTextBox1.AppendText("TryCatchReturn -> Outer" + Environment.NewLine);
}