java异常处理2

package lianxi3;
//异常处理方法二:当在此方法出现异常时,抛出一个异常类的对象,抛给方法的调用
//者。异常的对象可以逐层向上抛,直到main中,在抛的过程中,也能用try-catch
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class TestException {

    public static void main(String[] args){
    try{
        method2();
    }catch(FileNotFoundException e){
               System.out.println(e.getMessage());
   }catch(IOException e){
           e.printStackTrace();
   }
}
public static void method2()  throws FileNotFoundException,IOException{
 method1();
}
public static void method1()  throws FileNotFoundException,IOException{
    FileInputStream fis = new FileInputStream(new File("Hello.txt"));
    int str;
    while((str=fis.read())!=-1){
        System.out.print((char)str);
    }
    fis.close();
}
   
}

异常处理三: 手动抛出异常

抛出的异常类型,若是RuntimeException可以不显示的进行处理。

若是一个Exception,必须要显式的处理。如 throw new RuntimeException(“传入的类型有误!”);

posted on 2014-12-04 22:22  追梦的小屁孩  阅读(135)  评论(0编辑  收藏  举报