AutoCloseable-ish method but runs only on catch

Related searches

I would like to two have two different methods running in catch and final blocks. I have found AutoCloseable interface, but I need something to fire in case of exception only. Like:

SomeService service = CreateService().andOpenTransaction()

try {
} catch (Exception e) {
    throw e;
} finally {

Is there any way to make it simpler? As I said I am familiar with AutoCloseable, but it helps me only with finally block. I still cannot use it inside the catch.

Well you could define your own interface, and then some static runner method:

public interface ErrorHandlingCloseable extends AutoCloseable {
     void run() throws Exception;
     void onError(Exception e);

     static void execute(ErrorHandlingClosable ehc) throws Exception {
         try(ErrorHandlingClosable temp = ehc) {
         } catch(Exception e) {
             throw e;

Which you then could then call like this:

SomeService service = CreateService().andOpenTransaction();
ErrorHandlingCloseable.execute(new ErrorHandlingCloseable() {
    public void run() throws Exception { service.doSomeMessyThingsInsideDB(); }
    public void onError(Exception e) { service.rollbackTransaction(); }
    public void close() throws Exception { service.closeConnection(); }

But you see, it's still messy.

You could even implement this interface in your SomeService but then you're restricted that the run() method will always call doSomeMessyThingsInsideDB().

Another way but still similar would be to use Java8 and create a helper functional interface:

public interface ThrowingRunnable {
   void run() throws Exception;

And then a static method somewhere:

public static void execute(ThrowingRunnable action,
                           ThrowingRunnable onCatch,
                           ThrowingRunnable onFinally) throws Exception {
   try(AutoCloseable ao = onFinally) {;
   } catch(Exception e) {;
       throw e;

The interesting part is probably this: try(AutoCloseable ao = onFinally), which "registers" your onFinally method to be called when finally is reached.

This could then be called like this:


AutoCloseable-ish method but runs only on catch, I would like to two have two different methods running in catch and final blocks. I have found AutoCloseable interface, but I need something to� 2 AutoCloseable-ish method but runs only on catch Feb 14 1 Post controller recognizes only parameters sent by “from-data” or “x-www-form-urlencoded” from postman Mar 26 '19 1 Running 'install' command on dockerised App Service in Azure Apr 29 '19

You said you are familiar with AutoCloseable, but you don't use it. Have you considered using try-with-resources statement?

Your code can be simplified to:

try (SomeService service = CreateService().andOpenTransaction()) {
} catch(exception e){
    throw e;

Oracle has great doc for that, including examples.

Note: A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

Answering your question, this is as simple as it can get. If your class doesn't implement Closeable then you can either implement it or use finally.

The try-with-resources Statement, AutoCloseable , which includes all objects which implement the try statement completes normally or abruptly (as a result of the method BufferedReader. Note: A try -with-resources statement can have catch and finally blocks just like an In a try -with-resources statement, any catch or finally block is run after the� When the user double-clicks the Infolog message, the method is run. You can write code in the run method that helps to diagnose or fix the problem that caused the exception. You can write code in the run method that helps to diagnose or fix the problem that caused the exception.

First step: Handling the exception

You evidently want the exception handled before some close. Then you need inside a try-with-resources to handle the exception.

/** throws RuntimeException */
void process(Callable<Void> work, Consumer<Exception> onFail) {
    try {;
    } catch (Exception e) {

try (SomeService service = CreateService().andOpenTransaction()) {
    process(() -> service.doSomeMessyThingsInsideDB(),
            e -> {
                throw new IllegalStateException(e);

This is not very satisfactory, but again also integrating the AutoCloseable, might give too few use-cases.

Second step: with AutoCloseable

<SV extends AutoCloseable> void processAutoClosing(Supplier<SV> serviceFactory,
                                               Callable<Void> work, Consumer<Exception> onFail) {
try (SV service = serviceFactory.get()) {
    process(work, onFail);



The try-with-resources Statement in Java, The resources opened in the parentheses after the try statement will only be needed try-with-resources works the same as try-catch-finally, except with one small addition. For example, here's a resource that does nothing but throw exceptions: public static class MyResource implements AutoCloseable { // method throws� Previous Next Yes, we can have try without catch block by using finally block. You can use try with finally. As you know finally block always executes even if you have exception or return statement in try block except in case of System.exit(). Lets understand with the help of example. When you execute above program, you will get following output: What happens when you have return statement in

The AutoCloseable Interface. A Bit of Background, If you don't close the resources you are using, eventually you will run out of Autocloseable adds more to the Closeable interface, but this was The AutoClosable interface only came along with Java 1.7. and the An example of a method that could try and access the resource of a catch (Exception e) { Tasks executed by calling the RunSynchronously method are instantiated by calling a Task or Task<TResult> class constructor. The task to be run synchronously must be in the Created state. A task may be started and run only once. Any attempts to schedule a task a second time results in an exception. See also. Exception Handling (Task Parallel

Coding Rules, catch (Exception e) { // Noncompliant - exception is lost (only message is preserved) Preferably, when class implements AutoCloseable , resource should be An infinite loop is one that will never end while the program is running, i.e., you like a tidy way to get your classes what they need to do their jobs, but it's really a� I only tend to use this approach if I need a dedicated thread for a single task that is running for the lifetime of my application. ThreadPool The ThreadPool was introduced fairly early on in .NET (v1.1 I think) and provided an extremely simple way to request that your method be run on a thread from the thread pool.

Exception handling (Task Parallel Library) 04/20/2020; 14 minutes to read +6; In this article. Unhandled exceptions that are thrown by user code that is running inside a task are propagated back to the calling thread, except in certain scenarios that are described later in this topic.

  • There's no such interface for when exception is caught, auto-closeable is all there is. You could write a function with lambdas though.
  • Why do you have this transaction stuff external from the service to begin with?
  • Your solution also missing andOpenTransaction() part.
  • @M.Prokhorov thanks, I've added it before the method is executed.
  • looks cool, but a bit overengeenered. Actually You answered my question, so points are going to you anyway :)
  • @Arkadiusz your welcome, I've added another way to do what you desire, by using Java8 functional interfaces. Which is still a bit, but less overengineered
  • I am afraid I cannot use "service" variable in catch block. That is my problem.
  • if compiler would let me left the code the way you wrote I would have no problem at all. I am just looking for the best pattern :) looks like "try-with-resources" is not for me in this case. If noone will figure something out to the end of the day I will mark your answer as "the answer".