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 {
    service.doSomeMessyThingsInsideDB();
} catch (Exception e) {
    service.rollbackTransaction();
    throw e;
} finally {
    service.closeConnection();
}

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) {
             ehc.run();
         } catch(Exception e) {
             ehc.onError(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) {
       action.run();
   } catch(Exception e) {
       onCatch.run();
       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:

execute(
    service::doSomeMessyThingsInsideDB, 
    service::rollbackTransaction, 
    service::closeConnection
);

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()) {
    service.doSomeMessyThingsInsideDB();
} catch(exception e){
    service.rollbackTransaction();
    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 java.io. 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 SysInfoAction.run 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 {
        work.call();
    } catch (Exception e) {
        onFail(e);
    }
}

try (SomeService service = CreateService().andOpenTransaction()) {
    process(() -> service.doSomeMessyThingsInsideDB(),
            e -> {
                service.rollbackTransaction();
                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);
}

}

processAutoClosing(...);

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.