日期:2014-05-20  浏览次数:20703 次

关于异常的小问题,急,跪求~
看了书然后随便写了个测试,结果有问题,我新手,实在找不出问题所在,跪求前辈指点啊!!!!
import   java.io.*;

class   MakeException{
void   g(){
try{
throw   new   FileNotFoundException();
}catch(Exception   e){
throw   new   RuntimeException(e);
}
}
}
public   class   LostException{
public   static   void   main(String[]   args){
        MakeException   temp=new   MakeException();
try{
temp.g();
}catch(RuntimeException   re){
try{
throw   re.getCause();
}
catch(FileNotFoundException   e){
e.printStackTrace();
}
}
}
}
-----------------
错误提示是unreported   exception   java.lang.Throwable;   must   be   caught   or   declared   to   be   thrown
                                                throw   re.getCause();

------解决方案--------------------
import java.io.*;

class MakeException{
void g(){
try{
throw new FileNotFoundException();
}catch(Exception e){
throw new RuntimeException(e);
}
}
}
public class Test{
public static void main(String[] args){
MakeException temp=new MakeException();
try{
temp.g();
}catch(RuntimeException re){
try{
throw re.getCause();//因为getCause返回的是个Throwable类型,所以必须对Throwable进行捕获

}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(Throwable t) //加上这句
{
}

}
}
}

------解决方案--------------------
因为你的re.getCause()返回的是一个
Throwable对象
虽然这个Throwable对象是FileNotFoundException
但是没有强制向下转型
所以要求catch捕捉Throwable的异常