本文介绍了返回语句的最后一个块中的代码编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 以下是我的计划。Below is my program.class Program { int ret = default(int); static void Main(string[] args) { Program ob = new Program(); Console.WriteLine(ob.DoSomeOperation()); Console.WriteLine("------------------------------------"); //Console.WriteLine(ob.ret); Console.ReadKey(); } public int DoSomeOperation() { try { ret = 5; //return ret; } catch (Exception) { throw; } finally { ret = 9; } return ret; } } 你可以在try和最终看到里面看到return语句。 如果我在try块中取消注释return语句,DoSomeOperation方法将返回5,相反它将返回9. 请告诉我,如果finally块一直执行,那么为什么它不返回9如果我在try块中取消注释return语句。You can see the return statement inside try and after finally.If I uncommented the return statement in try block, DoSomeOperation method will return 5 and on the contrary it will return 9.Please clarify me if finally block executes all the time, then why it is not returning 9 if i uncommented the return statement in try block.推荐答案 Quote:如果return语句是在try块中,finally块(如果存在)将在控制返回到调用方法之前执行。If the return statement is inside a try block, the finally block, if one exists, will be executed before control returns to the calling method. 因此,它将执行finally块而不是到达最终的重新运行行。 (您的IDE可能显示您检测到无法访问的线路警告)So, it will execute finally block and not reach the final rerun line. (Your IDE may be showing you have unreachable line detected warning) 这篇关于返回语句的最后一个块中的代码编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-24 09:47