这个程序是 thinking in java 中的一段代码import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.Logger;
class Oops1 extends Exception{
private static Logger logger=Logger.getLogger("Oops1");
public Oops1(){
StringWriter trace=new StringWriter();
printStackTrace(new PrintWriter(trace));
logger.severe(trace.toString());
}
}
class Oops2 extends Exception{
private static Logger logger=Logger.getLogger("Oops2");
public Oops2(){
StringWriter trace=new StringWriter();
printStackTrace(new PrintWriter(trace));
logger.severe(trace.toString());
}
}public class Ex6 {
public static void f() throws Oops2,Oops1{
System.out.println("throwing Oops1 from f()");
throw new Oops1();
}
public static void g() throws Oops2{
System.out.println("throwint Oops2 from g()");
throw new Oops2();
}
public static void main(String[] args) {
try{
f();
}catch(Exception Oops1){
//e.printStackTrace();
}
try{
g();
}catch(Exception Oops2){
//e.printStackTrace();
}

}
}我当时写的时候用的是public static void main(String[] args) {
try{
f();
}catch(Oops1 e){
//e.printStackTrace();
}
try{
g();
}catch(Oops2 e){
//e.printStackTrace();
}

}编译不通过根据eclipse的提示解决方法是在main函数中抛出一个  Oops2 的异常但是为什么原程序不需要再main函数中抛出一个Oops2的异常呢?这两种抛出异常的方式有什么不同啊??

解决方案 »

  1.   

    因为原程序捕获的异常是Exception。它是Oops1,Oops2的基类
      

  2.   

    原程序中捕捉的是Exception
    public static void main(String[] args) {
    try{
    f();
    }catch(Exception Oops1){
    //e.printStackTrace();
    }
    try{
    g();
    }catch(Exception Oops2){
    //e.printStackTrace();
    }
      

  3.   

    你看看f();方法抛出的是2个Exception即Oops1和Oops2,你的main方法中只捕获了一个Oops1而已。
    而原程序里面的意思的捕获所有的Exception,也就是说包含了Oops1和Oops2,从Exception的类型可以看出来。
      

  4.   

    public static void f() throws Oops2,Oops1{
    System.out.println("throwing Oops1 from f()");
    throw new Oops1();
    }虽然实际上只抛出了一个异常,但是生命的时候,却是抛了两个,编译器编译的时候,不能确定到底抛了几个,多以自然就以声明为准了!!