当类不需要抛出异常时

时间:2014-12-05 16:44:28

标签: java exception

我制作了这个代码并且编译正确并且我得到了(hello 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");
  }   
}

1 个答案:

答案 0 :(得分:0)

该程序抛出了RuntimeException,但是你吞下了#34;只需打印出#34;抓住"

忽略对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 ");
}
}

打印:     hello throwit在

之后最终捕获了类java.lang.RuntimeException