2017-04-11 64 views
-1

免责声明:我没有访问java编译器也不能安装IDE,我的工作空间不给我足够的权限。是否明确抛出异常向上抛出?

我试图理解Java是如何处理异常交易和偶然发现了这个问题:

如果子类明确地抛出捕获所有异常的catch块中的例外,它是泛起?例如,考虑下面的代码行:

public Class someClass { 
    public int value; 
    public someClass() { 
     value = 1; 
     try { 
      value ++; 
      if(value == 2) { 
       throw new Exception("value is 2"); 
      } 
     } catch (exception e) { 
      System.out.println("I caught an exception."); 
      throw new Exception("Does this exception get thrown upwards?"); 
      System.out.println("will this line of code get printed after the previously thrown exception?"); 
     } finally { 
      return; 
     } 
    } 
} 

public class anotherClass { 
    public static void main throws Exception{ 
     someClass someclass = new someClass(); // will this class catch the second explicitly thrown exception? 
    } 
} 

因此,一个新的异常是在try块抛出,通过下面的catch块捕获。第二个投掷陈述去哪里?如果有的话,它会进入调用类吗?另外,println语句会在引发异常后执行,即使它不在finally块中?

谢谢。

+3

您已拥有该代码。你为什么不跑它看看会发生什么? –

+0

是的,第二个冒泡并且抛出后的'println'语句不会被执行。一个好的IDE将显示第二个'println'作为不可达代码。尝试Eclipse和FindBugs插件。 –

+0

@ThomasWeller我目前的工作电脑没有Java,我没有安装Java的权限,我也不能联系管理员。 – noobcoder

回答

1

第二个throw语句在哪里呢?如果有的话,它会向上进入 呼叫班吗?

是的,例外情况将抛出给调用方法,在你的情况下,它是main()方法。

即使它不在finally块中,println语句在抛出异常后会被执行 ?

是,System.out.println("I caught an exception.")将被执行,然后该异常对象将被抛出给调用者(即,main()),所以在catch块,下面的线不可达。

System.out.println("will this line of code get 
       printed after the previously thrown exception?"); 

重要的一点是,你可以随时使用exception.printStackTrace()(在catch块内)检查如何异常已经越过方法堆栈传播。我建议你尝试一下,这样你就可以清楚地看到异常是如何在方法中传播的。

我建议你参考here并清楚地了解方法链如何执行。

此外,另一点是,你可能会感兴趣的是,当main()方法抛出异常(即,main()本身或通过链条,无论是这种情况),那么JVM可以捕获该异常,并关闭

+0

谢谢你的洞察! – noobcoder

1

虽然可能不是预期,除了将可以在特定情况下,您也可以通过在someClass构造失踪throws条款看泛起。

原因是finally块中的return语句,导致java抛弃异常(以及一个好的IDE给你一个“finally块不能正常完成”的警告)。

更具体地,section 14.20.2 of the specification指出:

如果catch块为原因 - [R突然结束,然后执行最后 块。然后有一个选择:

  • 如果如果finally块的原因小号突然完成了finally块正常完成,则try语句的原因突然完成R.

  • ,那么try语句完成突然出于原因S(并且理由R被丢弃)。

随着原因小号作为return声明和原因[R作为throw new Exception("Does this exception get thrown upwards?");

您可以看到自己on ideone.com

class someClass { 
    public int value; 

    public someClass() { 
     value = 1; 
     try { 
      value++; 
      if (value == 2) { 
       throw new Exception("value is 2"); 
      } 
     } catch (Exception e) { 
      System.out.println("I caught an exception."); 
      throw new Exception("Does this exception get thrown upwards?"); 
     } finally { 
      return; 
     } 
    } 
} 

class anotherClass { 
    public static void main(String[] args) { 
     try { 
      someClass someclass = new someClass(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 

输出:

I caught an exception. 

但对于这个问题的目的,javaguy的答案已经覆盖了普遍的观点不够好。