示例代码:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms;
namespace 捕获异常问题 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private void button1_Click(object sender, EventArgs e) { Console.WriteLine("---------"+test()); }
public int test() { try{ Console.WriteLine("正常1"); throw new Exception(); Console.WriteLine("正常2"); return 0;//第1句
}catch(Exception ex) { Console.WriteLine("异常"); return 1;//第2句
}finally { Console.WriteLine("最终"); return 2;//第3句 }
return 3;//第4句
} } }
第一种情况:所有语句不屏蔽,输出结果会报错:控制不能离开 finally 子句主体,说明finally不能有return 语句
第二情况:屏蔽第3句,输出
正常1 异常 最终 ---------1
情况分析:抛出异常后,先执行catch里面的语句,有return会先执行finally里面语句然后return
第三情况:屏蔽第2句,第3句,输出
正常1 异常 最终 ---------3
这种情况很好理解
以上基本就是这些常见问题了