【问题标题】:Is there a way to simplify the try-catch block within another try-catch-finally block?有没有办法在另一个 try-catch-finally 块中简化 try-catch 块?
【发布时间】:2016-02-25 03:51:06
【问题描述】:

我是 Java 新手,正在尝试学习捕获异常的概念。我在网上看到了这段代码,它在另一个 try-catch-finally 块的主体内有一个 try-catch 块。我只是想知道是否有任何方法可以简化代码以便以更清晰的方式编写?

public static void main(String[] args) {
    Properties p1 = new Properties();
    OutputStream os1 = null;

    try {
        os1 = new FileOutputStream("xanadu123.properties");

        //set the properties value
        p1.setProperty("database", "localhost");
        p1.setProperty("1", "one");
        p1.setProperty("2", "two");

        p1.store(os1, "this is the comment");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (os1 != null) {
            try {
                os1.close();
            } catch (IOException e){
                e.printStackTrace();
            }
        }   
    }

【问题讨论】:

    标签: java exception exception-handling try-catch


    【解决方案1】:

    这确实是一个很常见的模式,所以最近在Java中添加了一个特殊的语法:try-with-resources

    你可以的

    try(OutputStream os1 = new FileOutputStream("xanadu123.properties")){
    }
    catch (WhatYouHadBefore e){}
    // no more finally, unless you want it for something else
    

    这将被finally 自动关闭(即使没有finally 块)并且关闭期间的任何错误都将被禁止。

    【讨论】:

      【解决方案2】:

      根据 javadocs,在 Java SE 7 及更高版本中,您可以使用try-with-resources,它会在完成后自动关闭资源。

      public static void main(String[] args) {
          Properties p1 = new Properties();
          OutputStream os1 = null;
          try(os1 = new FileOutputStream("xanadu123.properties")){ //set the properties value
              p1.setProperty("database", "localhost");
              p1.setProperty("1", "one");
              p1.setProperty("2", "two");
              p1.store(os1, "this is the comment");
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2011-06-01
        • 2011-08-31
        • 2012-03-06
        • 1970-01-01
        • 1970-01-01
        • 2015-09-05
        • 2013-12-16
        • 1970-01-01
        • 2019-02-28
        相关资源
        最近更新 更多