当前位置:编程学习 > JAVA >>

大牛们 提一个thinking in java 中有关异常捕获的问题

这个程序是 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的异常呢?

这两种抛出异常的方式有什么不同啊??

--------------------编程问答-------------------- 因为原程序捕获的异常是Exception。它是Oops1,Oops2的基类 --------------------编程问答-------------------- 原程序中捕捉的是Exception
public static void main(String[] args) {
try{
f();
}catch(Exception Oops1){
//e.printStackTrace();
}
try{
g();
}catch(Exception Oops2){
//e.printStackTrace();
}
--------------------编程问答-------------------- 我也不明白,那边声明,这边捕获,有什么不可? --------------------编程问答-------------------- 你看看f();方法抛出的是2个Exception即Oops1和Oops2,你的main方法中只捕获了一个Oops1而已。
而原程序里面的意思的捕获所有的Exception,也就是说包含了Oops1和Oops2,从Exception的类型可以看出来。 --------------------编程问答--------------------
引用 4 楼 qqhw123 的回复:
你看看f();方法抛出的是2个Exception即Oops1和Oops2,你的main方法中只捕获了一个Oops1而已。
而原程序里面的意思的捕获所有的Exception,也就是说包含了Oops1和Oops2,从Exception的类型可以看出来。



public static void f() throws Oops2,Oops1{
System.out.println("throwing Oops1 from f()");
throw new Oops1();
}



虽然实际上只抛出了一个异常,但是生命的时候,却是抛了两个,

编译器编译的时候,不能确定到底抛了几个,多以自然就以声明为准了!! --------------------编程问答--------------------
引用 4 楼 qqhw123 的回复:
你看看f();方法抛出的是2个Exception即Oops1和Oops2,你的main方法中只捕获了一个Oops1而已。
而原程序里面的意思的捕获所有的Exception,也就是说包含了Oops1和Oops2,从Exception的类型可以看出来。

原来声明了两个,哎,天黑没看清楚
补充:Java ,  Java SE
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,