Java异常机制

异常机制 Exception

/**
 * user try/catch/final
 */
public class Test {
    
    public void openFile(){
        try {
            FileReader fr = new FileReader("d:/test.txt");
            int a = fr.read();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            System.out.println("finally works!");
        }
    }
}

 

/**
 * use throws, 用throws的时候, 直接声明且抛出异常, 在方法具体被调用的地方做处理
 */
public class Test {

    public String openFile() throws FileNotFoundException, IOException {

            FileReader fr = new FileReader("d:/test.txt");
            char c = (char)fr.read();
            return "" +c;
    }

    public static void main(String[] args) {
        String str;
        try {
            str = new Test().openFile();        //调用方法时候做具体处理
        } catch (FileNotFoundException e){
            e.printStackTrace();
        } catch (IOException e ){
            e.printStackTrace();
        }finally {
            System.out.println("okay...");
        }
    }
}

 

posted on 2018-08-30 17:16  TheExile  阅读(155)  评论(0)    收藏  举报

导航