服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

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


  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了。

扫描关注微信公众号