Java- 受检的异常(checked Exception)

受检的异常

  • Exception分为两种
    1. RuntimeException及其子类,可以不明确处理,例如边界异常,解析整型时格式异常。
    2. 否则,称为受检的异常(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效果相同。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值