技术开发 频道

一个关于抛出异常的程序代码的分析

  【IT168 技术文档】一个关于抛出异常的程序代码的分析

  1. public class test {   2. public static string output = “”   3.   4. public static void foo(int i) {   5. try {   6. if(i= =1) {   7. throw new Exception ();   8. }   9. output +=1”;   10. )   11. catch(Exception e) {   12. output +=2”;   13. return;   14. )   15. finally (   16. output +=3”;   17. )   18. output +=4”;   19. )   20.   21. public static void main (string args[]) (   22. foo(0);   23. foo(1);   24.   25. )   26. )

  What is the value of the variable output at line 24?

  Ans: 13423

  答案怎么会输出5个数字呢?

  首先,foo(0),就直接到第9行。output=1

  然后,因为没有抛出异常,所以直接运行16行。

  然后运行18行。此时,output=134.

  foo(1),因为抛出异常,所以运行12行。

  然后因为catch了异常,然后运行finally里的语句。

  但是18行的不再被运行,因为13行已经要求return了。

0
相关文章