zoukankan      html  css  js  c++  java
  • Java中try()catch{}的使用方法

    今天撸代码的时候发现了一段这样的代码

    try(
                Connection conn=DriverManager.getConnection(url,user,pass);
                Statement stmt=conn.createStatement()
     
             ) {
     
                boolean hasResultSet=stmt.execute(sql);
     
               }

      和平常见的不一样,我们平常见的是这样的

    try{
            fis=new FileInputStream("src\com\ggp\first\FileInputStreamDemo.java");
            byte[]bbuf=new byte[1024];
            int hasRead=0;
            while((hasRead=fis.read(bbuf))>0){
          
            System.out.println(new String(bbuf,0,hasRead));
     
            }
     
            }catch(IOException e){
            e.printStackTrace();
            }finally{
            try {
                 fis.close();
                 } catch (IOException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
                }
     
            }

      如果{}中的代码块出现了异常,会被catch捕获,然后执行catch中的代码,接着执行finally中的码,其中catch中的代码有了异常才会被执行,finally中的代码无论有没有异常都会被执行,

          而第一种情况的()中的代码一般放的是对资源的申请,如果{}中的代码出项了异常,()中的资源就会被关闭,这在inputstream和outputstream的使用中会很方便例如

    private static void customBufferStreamCopy(File source, File target) {
        try (InputStream fis = new FileInputStream(source);
            OutputStream fos = new FileOutputStream(target)){
      
            byte[] buf = new byte[8192];
      
            int i;
            while ((i = fis.read(buf)) != -1) {
                fos.write(buf, 0, i);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
     

    从网上查阅资料得知从 Java 7 build 105 版本开始,Java 7 的编译器和运行环境支持新的 try-with-resources 语句,称为 ARM 块(Automatic Resource Management) ,自动资源管理。

    The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

    带有resources的try语句声明一个或多个resources。resources是在程序结束后默认掉resources.close(),关闭的资源对象。try-with-resources语句确保在语句末尾关闭每个resources。任何实现java.lang.AutoCloseable,包括实现了java.io.Closeable的类,都可以作为resources使用

  • 相关阅读:
    4408: [Fjoi 2016]神秘数
    UOJ #35. 后缀排序[后缀数组详细整理]
    POJ 2887 Big String
    搜索过滤grep(win下为findstr)
    解决putty自动断开的问题
    > >> 将错误输出到文件
    环境变量
    端口被占用,查看并杀死占用端口的进程
    查找文件路径find
    【vim使用】
  • 原文地址:https://www.cnblogs.com/skyblue123/p/13501246.html
Copyright © 2011-2022 走看看