Reasons and scenarios for using try and finally not using catch
In the JDK concurrency toolkit, many exception handling uses the following structure, such as AbstractExecutorService, that is, there is only try and finally 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 are the benefits? Look at the following code first
public void testTryAndFinally(String name) { try { name.length();// NullPointerException } finally { System.out.println("aa"); } }The execution result of passing null The method is: print aa on the console and throw a NullPointerException. The execution process is to first execute the try block, execute the finally block after an exception occurs, and finally throw an exception in the try to the caller. This execution result is very normal, because there is no catch exception handler, all methods can only throw the generated exception outward; because there is finally, before the method returns to throw an exception, the final code block will be executed. Cleaning up.
What are the benefits of this approach? For testTryAndFinally, it does what it must do and throws exceptions that it cannot handle; for the caller, it can perceive the exceptions that appear and can handle them as needed. In other words, this structure realizes the separation of responsibilities, realizes the decoupling of exception handling and exception cleaning, and allows different methods to focus on what they should do. So when to use try-finally, and when to use try-catch-finally? Obviously it depends on whether the method itself can handle exceptions that appear in the try. If you can handle it yourself, then catch it directly without throwing it to the caller of the method; if you don't know how to deal with it, you should throw the exception outward, so that the caller knows that an exception has occurred. That is, declare an exception that throws may appear in the signature of the method and cannot be handled by itself, but do what you should do within the method.
The situation where the finally statement will not be executed
The only situation where Java's finally statement will not be executed is that the System.exit() method used to terminate the program is executed first.
public class Test { public static void main(String[] args) { try { System.out.println("Start"); System.exit(0); } finally { System.out.println("F inally"); } System.out.println("End"); } }The output result is:
Start
Of course, if the power is suddenly cut off when executing a general try statement without the System.exit() statement, all processes will terminate and the finally statement will not be executed.