Java中try()catch{}的使用方法

小灰灰 2021-01-22 05:48 1297阅读 0赞

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

  1. try(
  2. Connection conn=DriverManager.getConnection(url,user,pass);
  3. Statement stmt=conn.createStatement()
  4. ) {
  5. boolean hasResultSet=stmt.execute(sql);
  6. }
  7. 和平常见的不一样,我们平常见的是这样的
  8. try{
  9. fis=new FileInputStream("src\\com\\ggp\\first\\FileInputStreamDemo.java");
  10. byte[]bbuf=new byte[1024];
  11. int hasRead=0;
  12. while((hasRead=fis.read(bbuf))>0){
  13. System.out.println(new String(bbuf,0,hasRead));
  14. }
  15. }catch(IOException e){
  16. e.printStackTrace();
  17. }finally{
  18. try {
  19. fis.close();
  20. } catch (IOException e) {
  21. // TODO Auto-generated catch block
  22. e.printStackTrace();
  23. }
  24. }

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

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

  1. private static void customBufferStreamCopy(File source, File target) {
  2. try (InputStream fis = new FileInputStream(source);
  3. OutputStream fos = new FileOutputStream(target)){
  4. byte[] buf = new byte[8192];
  5. int i;
  6. while ((i = fis.read(buf)) != -1) {
  7. fos.write(buf, 0, i);
  8. }
  9. }
  10. catch (Exception e) {
  11. e.printStackTrace();
  12. }
  13. }

从网上查阅资料得知从 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是在程序结束后必须关闭的对象。try-with-resources语句确保在语句末尾关闭每个resources。任何实现java.lang.AutoCloseable,包括实现了java.io.Closeable的类,都可以作为resources使用。

发表评论

表情:
评论列表 (有 1 条评论,1297人围观)
朱雀
朱雀V铁粉 2021-06-20 10:14
Addoil.png

相关阅读

    相关 javatryCatch

    在进行代码编写的时候我们其实是不能预料到所有的可能出现的结果的因为实际使用的用户他是不知道我们的实现逻辑的所以呢,他们的操作也是离奇的怪的,所以我们是不能控制用户输入怎样的操作