2014-12-05 97 views
-2

我做了这个代码,它正确编译和我有(你好throwit终于抓到后) 但还是不知道为什么类RTExcept没有扔RuntimeException (public class RTExcept throws RuntimeException {})当类不需要抛出异常

public class RTExcept { 

public static void throwit(){ 
     System.out.print("throwit "); 
     throw new RuntimeException(); 
    } 

public static void main(String[] args) { 
    try{ 
    System.out.print("hello"); 
    throwit(); 
    } catch (Exception e){ 
    System.out.print("caught"); 
    } finally{ 
    System.out.print("finally"); 
    } 
    System.out.print("after"); 
    } 
} 
+3

'RuntimeException'和它的任何子类不需要'throws'指定。 – 2014-12-05 16:46:09

+1

如果方法中可能发生“checked”异常,那么方法必须使用try/catch来抑制可能的异常,或者必须通过方法头上的'throws'子句声明异常的可能性。但并非所有异常都处于“checked”类别中 - 只有“Exception”类的Throwable类,“RuntimeException”的子类不是“checked”。 – 2014-12-05 16:52:25

+0

Exception的规范说:*类Exception和任何不属于RuntimeException子类的子类都是检查异常。检查异常需要在方法或构造函数的throws子句中声明,如果它们可以通过执行方法或构造函数来抛出并传播到方法或构造函数边界之外的话。* – 2014-12-05 16:53:16

回答

0

该程序引发了一个RuntimeException,但您只是通过打印出“捕获”来“吞下”异常。

您忽略对RuntimeException catch块的引用。将e.getClass()追加到下面的System.out中,您将看到RuntimeExcetion。

class RTExcept { 
public static void throwit(){ 
    System.out.print("throwit "); 
    throw new RuntimeException(); 
} 
public static void main(String[] args) { 
    try{ 
     System.out.print("hello "); 
     throwit(); 
    } catch (Exception e){ 
     System.out.print(" caught " + e.getClass()); 
    } finally{ 
     System.out.print(" finally "); 
    } 
    System.out.print(" after "); 
} 
} 

打印: 你好throwit抓阶级了java.lang.RuntimeException后终于

+0

雅,这是正确的......谢谢 – DeepBlue0003 2014-12-05 16:58:50

+0

没问题:)但请记住你对你的问题的评论。能够区分检查和未检查的异常是非常重要的。 – thomas77 2014-12-05 17:04:23

+0

现在我做了,再次感谢 – DeepBlue0003 2014-12-05 17:09:03