Search code examples
javatry-catch

Search for more elegant way to handle many nested try with resources


I am searching for more elegant way to handle problems where we need to have many nested try with resources ,which are dependednt from one another. Example of such case:

        try (MDC.MDCCloseable test= MDC.putCloseable("test", test)) {
        try (MDC.MDCCloseable paw= MDC.putCloseable("paw", test.getPaw().toString())) {
           try (MDC.MDCCloseable tru = MDC.putCloseable("tru", paw.getTRU().toString())) {
              try (MDC.MDCCloseable mdcKey = MDC.putCloseable("rtu", paw.getKey())) {
                 try (MDC.MDCCloseable rtu= MDC.putCloseable("rtu", "test")) {
                    try (MDC.MDCCloseable ito= MDC.putCloseable("ito", rtu.getIto())) {
                        ...
                    }
                 }
                 try (MDC.MDCCloseable eht = MDC.putCloseable("eht", "eht")) {
                       try (MDC.MDCCloseable epr= MDC.putCloseable("epr", eht.getEPR())) {
                       }
                 }
                 try (MDC.MDCCloseable lkt = MDC.putCloseable("lkt", "lkt")) {
                    try (MDC.MDCCloseable plo= MDC.putCloseable("plo", lkt.getPlo())) {
                    }
                 }
              }
           }
        }
     }

Solution

  • Why not to put all resources to the same try?

    Here is simplified example:

    try (MDC.MDCCloseable test= MDC.putCloseable("test", test);
         MDC.MDCCloseable paw= MDC.putCloseable("paw", test.getPaw().toString()) {
        /// etc, etc.
    }