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的使用中会很方便例如

   
  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.io.ObjectInputStream;
  import java.io.ObjectOutputStream;
   
  /**
  * 对象的序列化
  *
  * @author by Young.ZHU
  * on 2016年5月29日
  *
  * Package&FileName: org.young.elearn.str.io.ObjectSerialize
  */
  public abstract class ObjectSerialize {
   
  /**
  * 将对象存储到文件中
  *
  * @param obj - 要存储的对象
  * @param destFile - 存储的文件名
  * @throws IOException
  */
  public static void writeObject(Object obj, String destFile) {
  // 如果目录不存在,则创建
  String pathStr = destFile.substring(0, destFile.lastIndexOf("\\"));
  // System.out.println(pathStr);
  File pathObj = new File(pathStr);
  if (!pathObj.exists()) {
  pathObj.mkdir();
  }
   
  File file = new File(destFile);
   
  // 放在try里会自动关闭(close)资源
  try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));) {
  oos.writeObject(obj);
  System.out.println("object written.");
  } catch (IOException e) {
  e.printStackTrace();
  }
  }
   
  /**
  * 从文件中读取对象
  *
  * @param sourceFile - 存储对象信息的文件
  * @return
  */
  public static Object readObject(String sourceFile) {
  Object obj = null;
  try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(sourceFile));) {
  obj = ois.readObject();
  } catch (Exception e) {
  e.printStackTrace();
  }
   
  return obj;
  }
  }

猜你喜欢

转载自blog.csdn.net/qq_33543634/article/details/80725899