zoukankan      html  css  js  c++  java
  • 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❤涛
  • 相关阅读:
    MVC HtmlHelper
    Bellman-ford算法、SPFA算法求解最短路模板
    Dijkstra算法求最短路模板
    静态邻接表模板
    HDU 4511 小明系列故事——女友的考验 ( Trie图 && DP )
    HDU 4758 Walk Through Squares ( Trie图 && 状压DP && 数量限制类型 )
    HDU 3341 Lost's revenge ( Trie图 && 状压DP && 数量限制类型 )
    POJ 3691 DNA repair ( Trie图 && DP )
    POJ 2456 Aggressive cows ( 二分 && 贪心 )
    HDU 2296 Ring ( Trie图 && DP && DP状态记录)
  • 原文地址:https://www.cnblogs.com/aikutao/p/15724168.html
Copyright © 2011-2022 走看看