突然遇到一个疑问:当try...catch...finally同时存在的时候,怎样才能跳出catch,而不执行finally里面的语句,我做了如下两种测试(return和goto),均发现finally无论什么情况下都一定会执行的。如下:
using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { Demo("3.5"); } static void Demo(string num) { try { int a = int.Parse(num); } catch(Exception ex) { Console.WriteLine(ex.Message); return;//goto aaa; } finally { Console.WriteLine("我执行了!"); Console.ReadLine(); } aaa: Test(); } static void Test() { Console.WriteLine("跳到我这里了!"); Console.ReadLine(); } } }
当遇到这个问题的时候,我在思考这样的情况发生时就存在return和goto与finally的矛盾,后来查看了某些资料,才知道它是跟IL层有关系,结论是在IL层跳出catch块会出现一个leave.s,这个leave.s会确保finally块的执行,所以,即使在catch中使用了return语句想直接跳出,还是会先执行finally再return的。
OK~结论就是无论在catch中放入什么东西来打断语句的执行都是不可能的,相反它会先执行finally再返回到需要跳出或者是跳转的语句块。