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


     第一种写法:

      try(InputStream is=new FileInputStream("C:\\Users\\Administrator\\Desktop\\project\\test.txt")){
    
                /*........................................*/
    
            } catch (Exception e) {
                e.printStackTrace();
       }
    

      

    第二种写法:

          try  {
                InputStream is=new FileInputStream("C:\\Users\\Administrator\\Desktop\\project\\test.txt")
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                
            }
    

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

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

      从 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使用。

    MC❤涛
  • 相关阅读:
    基于jQuery的上下无缝滚动应用(单行或多行)
    表单验证
    中国剩余定理 ( 的学习 )
    扩展欧几里德算法--学习笔记
    Vijos P1794 文化之旅
    1336 : Matrix Sum (hihocoder)
    nyoj 1030 hihocoder 1338
    多重邻接表
    图的存储 ( 十字链表 )
    01背包的变形
  • 原文地址:https://www.cnblogs.com/aikutao/p/15724168.html
Copyright © 2020-2023  润新知