java 最后在里面使用try catch可以吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3051276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 00:06:54  来源:igfitidea点击:

Is it okay to use try catch inside finally?

javaexception-handling

提问by Hiral Lakdavala

I am using a buffered writer and my code, closes the writer in the finally block. My code is like this.

我正在使用缓冲编写器和我的代码,在 finally 块中关闭编写器。我的代码是这样的。

 ...........
    BufferedWriter theBufferedWriter = null;
    try{
    theBufferedWriter =.....
    ....
    ......
    .....
    } catch (IOException anException) {
    ....
    } finally {
        try {
            theBufferedWriter.close();              
        } catch (IOException anException) {
            anException.printStackTrace();
            }
    }

I have to use the try catch inside the clean up code in finally as theBufferedWriter might also throw an IOException. I do not want to throw this exception to the calling methos. Is it a good practice to use a try catch in finally? If not what is the alternative? Please suggest.

我必须在 finally 的清理代码中使用 try catch ,因为 BufferedWriter 也可能抛出 IOException。我不想将此异常抛给调用方法。最后使用 try catch 是一个好习惯吗?如果不是,有什么替代方案?请建议。

Regards, Hiral

问候, 希拉尔

采纳答案by Edward Dale

A somewhat nicer way to do this is to use IOUtils.closeQuietyfrom Apache commons-io. It keeps your code tidy and eliminates some of the boilerplate that's inherent in Java.

一个更好的方法是使用Apache commons-io 中的IOUtils.closeQuiety。它使您的代码保持整洁并消除了 Java 中固有的一些样板。

You code then becomes:

你的代码然后变成:

BufferedWriter theBufferedWriter = null;
try{
    theBufferedWriter = ...
    ...
} catch (IOException anException) {
    ...
} finally {
    IOUtils.closeQuietly(theBufferedWriter);
}

Much nicer and more expressive.

更好看,更有表现力。

回答by aioobe

In pre Java 7, I'd say what you have written is the best solution.

在 Java 7 之前,我会说你写的是最好的解决方案。

In Java 7 and onwards you have Automatic Resource Managementintended to simplify these things. With this feature, you can do

在 Java 7 及更高版本中,您拥有旨在简化这些事情的自动资源管理。有了这个功能,你可以做

BufferedWriter theBufferedWriter = null;
try (BufferedWriter theBufferedWriter = ...) {
....
......
.....
} catch (IOException anException) {
....
}

回答by Shervin Asgari

Or you can use Lombokand the @Cleanupannotation and you shall never write a try catch inside finally again.

或者你可以使用Lombok@Cleanup注解,你永远不会再在 finally 里面写一个 try catch 。

This is how you would normally write it (Note the throws IOException):

这是您通常的编写方式(注意throws IOException):

//Vanilly Java

import java.io.*;

public class CleanupExample {
  public static void main(String[] args) throws IOException {
    InputStream in = new FileInputStream(args[0]);
    try {
      OutputStream out = new FileOutputStream(args[1]);
      try {
        byte[] b = new byte[10000];
        while (true) {
          int r = in.read(b);
          if (r == -1) break;
          out.write(b, 0, r);
        }
      } finally {
        out.close();
      }
    } finally {
      in.close();
    }
  }
}

Now with Lombok you just write @Cleanupon the streams

现在有了 Lombok,您只需@Cleanup在溪流上书写

import lombok.Cleanup;
import java.io.*;

 public class CleanupExample {
   public static void main(String[] args) throws IOException {
     @Cleanup InputStream in = new FileInputStream(args[0]);
     @Cleanup OutputStream out = new FileOutputStream(args[1]);
     byte[] b = new byte[10000];
     while (true) {
       int r = in.read(b);
       if (r == -1) break;
       out.write(b, 0, r);
     }
   }
 }

回答by user85421

It's OK but you should test if theBufferedWriteris not null before closing it.
You could also do:

没关系,但您应该theBufferedWriter在关闭它之前测试它是否为空。
你也可以这样做:

BufferedWriter theBufferedWriter;
try {
    theBufferedWriter = new ...
    try {
        ...
    } finally {
        try {
            theBufferedWriter.close();
        } catch (IOException closeException) {
            closeException.printStackTrace();
        }
    }
} catch (IOException anException) {
    ...
}

or:

或者:

BufferedWriter theBufferedWriter;
try {
    theBufferedWriter = new ...
} catch (IOException createException) {
    // do something with createException 
    return;  // assuming we are in a method returning void
}

try {
    ...
} catch (IOException anException) {
    ...
    // assuming we don't return here
}

try {
    theBufferedWriter.close();
} catch (IOException closeException) {
    closeException.printStackTrace();
}

but mostly I do such operations (e.g. writing a file) in a dedicated method and prefer to throw the/an Exception so the caller can handle it (e.g. asking for another file, stopping the application, ...):

但大多数情况下,我在专用方法中执行此类操作(例如写入文件),并且更喜欢抛出 / 异常以便调用者可以处理它(例如,请求另一个文件,停止应用程序,...):

void someMethod(...) throws IOException {
    BufferedWriter theBufferedWriter = new ...

    try {
        ...
    } catch (IOExcepption anException) {
        try {
            theBufferedWriter.close();
        } catch (IOException closeException) {
            closeException.printStackTrace();
            // closeException is not thrown, anException represents the main/first problem
        }
        throw anException;
    }

    theBufferedWriter.close();  //  throws the Exception, if any
}

Please note: English is not my first nor my second language, any help would be appreciated

请注意:英语不是我的第一语言也不是我的第二语言,任何帮助将不胜感激

回答by krock

This is what we will have to live with until Java 7 and ARM Blocks.

这就是我们在 Java 7 和ARM Blocks之前必须忍受的。

回答by ILMTitan

It's ok to put a try-catch in a finally. It is the tool that does what you want to do. However, I feel the thrown IOException on close is uncommon enough that I would allow it to suppress any exception in the body like so.

可以将 try-catch 放入 finally 中。它是做您想做的事情的工具。但是,我觉得关闭时抛出的 IOException 并不常见,我会允许它像这样抑制主体中的任何异常。

try {
    BufferedWriter writer = .....
    try {
        .....
    } finally {
       writer.close();
    }
 } catch (IOException e) {
     ....
 }