In the JDK Concurrency Toolkit, many exception handling uses the following structure, such as Abstractexecutorservice, where only try and finally have no catch.
Class X { private final reentrantlock lock = new Reentrantlock (); // ... public void M () { lock.lock (); Block until condition holds try { //... method body } finally { lock.unlock () } }}
Why use this structure? What good is it? First look at the following code
Public void testtryandfinally (String name) { try { name.length (); // NullPointerException } finally { System.out.println ("AA");} }
Pass NULL The result of this method is: Print AA on the console and throw nullpointerexception. The execution process executes a try block first, executes a finally block after an exception occurs, and finally throws an exception in a try to the caller. The result of this execution is normal, because there is no catch exception handler, all of which can only throw out the resulting exception, because there is finally, the cleanup work in the finally code block is performed before the method returns the exception being thrown.
What are the benefits of this approach? For testtryandfinally, it does what it has to do (finally) and throws out an exception that it cannot handle, and for the caller, it can perceive the exception and handle it as needed. In other words, this structure realizes the separation of duties, realizes the decoupling of exception handling (throw) and exception Cleanup (finally), and lets different methods focus on what they should do. When do you use try-finally, and when do you use try-catch-finally? Obviously this depends on whether the method itself can handle the exceptions that occur in the try . If you can handle it, then catch it directly, without throwing it to the caller of the method, and if you don't know how to handle it, you should throw the exception out and let the caller know that an exception has occurred. That is, in the signature of the method, declare the exception that throws may appear and cannot handle, but do what you are supposed to do inside the method.
This can refer to the method signature of the Executorservice.invokeany ()
<T> T invokeany (collection<? extends callable<t>> tasks) throws Interruptedexception, Executionexception;
Transfer from Http://blog.csdn.net/aitangyong/article/details/38146833?utm_source=tuicool&utm_medium=referral
Java uses only try and finally causes and scenarios that do not use catch