Java- 受检的异常(checked Exception)

受检的异常

    Exception分为两种 RuntimeException及其子类,可以不明确处理,例如边界异常,解析整型时格式异常。 否则,称为受检的异常(checked Exception),更好的保护安全性 受检的异常,要求明确进行语法处理 要么捕获(catch) 要么抛出(throw):在方法的签名后面用throws xxx来声明 在子类中,如果要覆盖父类的一个方法,若父类中的方法声明了throws异常,则子类的方法也可以throws异常 可以抛出子类异常(更具体的异常),但不能抛出更一般的异常 public class ExceptionTrowsToOther{ public static void main(String[] args){ try{ System.out.println("====Before===="); readFile(); System.out.println("====After===="); }catch(IOException e){ System.out.println(e); }// catch the exception } public static void readFile()throws IOException { // throws exception FileInputStream in=new FileInputStream("myfile.txt"); int b; b = in.read(); while(b!= -1) { System.out.print((char)b); b = in.read(); } in.close(); } } -----------OUTPUT----------- ====Before==== java.io.FileNotFoundException: myfile.txt (The system cannot find the file specified)

try…with…resource

try(类型 变量名=new类型() ){
    ...
}

自动添加了finally{ 变量.close(); }对可关闭的资源进行关闭操作

static String ReadOneLine1(String path){
        BufferedReader br=null;
        try {
            br=new BufferedReader(new FileReader(path));
            return br.readLine();
        } catch(IOException e) {
            e.printStackTrace();
        } finally {
            if(br!=null){
                try{ 
                    br.close();
                }catch(IOException ex){
                }
            }
        }
        return null;
    }
    static String ReadOneLine2(String path)
        throws IOException
    {
        try(BufferedReader br= new BufferedReader(new FileReader(path))){
            return br.readLine();
        }
    }

上面两个函数ReadOneLine1及ReadOneLine2效果相同。

经验分享 程序员 微信小程序 职场和发展