Try-with-resources equivalent in Java 1.6

前端 未结 3 621
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 15:51

I have the following code:

    public class Main {

        public static void main(String[] args) throws SQLException {

            try (
                         


        
3条回答
  •  有刺的猬
    2020-11-28 16:32

    Oracle explains how try-with-resources works here

    The TL;DR of it is:
    There is no simple way of doing this in Java 1.6. The problem is the absence of the Suppressed field in Exception. You can either ignore that and hardcode what happens when both try AND close throw different exceptions, or create your own Exception sub-hierarchy that has the suppressed field.

    In the second case, the link above gives the proper way of doing it:

       AutoClose autoClose = new AutoClose();
       MyException myException = null;
       try {
           autoClose.work();
       } catch (MyException e) {
           myException = e;
           throw e;
       } finally {
           if (myException != null) {
               try {
                   autoClose.close();
               } catch (Throwable t) {
                   myException.addSuppressed(t);
               }
           } else {
               autoClose.close();
           }
       }  
    

    is equivalent to

    try (AutoClose autoClose = new AutoClose()) {
        autoClose.work();
    }
    

    In case you want to make it easier and not create a whole lot of new Exception classes, you will have to decide what to throw in the catch clause inside the finally (t or e).

    PS. Dealing with multiple variable declaration in the try is also discussed in the link above. And the amount of code that you need to do it properly is staggering. Most people take shortcuts in Java 1.6 by not coping with exceptions in the finally block and using nullchecks.

提交回复
热议问题