try catch finally
For all java developers, closing resources in a finally block of code is a familiar approach. Part of exception handling is to ensure that all kinds of resources in the code block are closed and effectively released. Once the code in the try catch statement block throws an exception, the previous workflow will change.
try { //code statements //Exception throw here //Lines not reached if exception throw } catch (Exception e) { //lines reached only when exception is thrown } finally { //always executed irrespective of an exception thrown or not //(the part of code that executes whether an exception is thrown or not) }
Obviously, in the above code, the best place to close and release various resources is the finally part. The resources mentioned here are specific instances or objects such as database connection, file connection, etc.
Execution order of finally
1. finally is not a necessary condition
In other words, in try catch finally, there can be only try catch or try finally.
2. Suppose based on try catch finally:
First: the code has no exception
Execution sequence: try execution complete - > catch execution not - > finally execution
Second: the code has an exception and catch it**
Execution sequence: try execution part - > jump to catch capture processing - > finally execution
Third: the code has exceptions and catch is not caught: there is no catch in this case**
Execution sequence: try execution part - > finally execution
From the above execution sequence, we can see that the finally statement will be executed no matter what the situation. Based on this understanding, now let's analyze it again.
Aside: when finally has a return, it will return directly. The return value in try or catch will not be returned. When finally there is no return, the return statements of try and catch will not be executed immediately. Instead, the values in try and catch will be returned after finally executing the code block.
Disadvantages of try finally
If multiple resources are opened at the same time, a nightmare scenario will appear:
Programmers have to explicitly close a resource, and have to repeatedly use the try catch statement in finally to process the closing statement, which is a typical redundant code in java programs.
... InputStream is = null; try { is = new FileInputStream("test"); is.read(); ... } catch (Exception e) { ... } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); ... } }
try-with-resources
Try with resources is a syntax sugar introduced in jdk1.7, so that closing resources does not need to be nested in finally. Automatically close resources
To use try-with-resource Resources must be realized first AutoCloseable Interface, which contains a single return void of close method, Java Many classes and interfaces in class libraries and third-party class libraries are now implemented or extended AutoCloseable Interface, so we don't have to implement it now.
The compiler will automatically complete the close() for us
The initialization of resources is done in try(). A pair of parentheses () are introduced after try to complete the initialization of resources. An example is as follows:
try (InputStream is = new FileInputStream("test")) { is.read(); ... } catch(Exception e) { ... } finally { //no need to add code to close InputStream, its close method will be internally called //(there is no need to add code to close the InputStream input stream, and its close() method will be called by itself) } In this way, does it feel that the code is much cleaner and leaves when the program runs try When a statement block,( )The resources in the will be automatically closed. however try-with-resources There are several key points to remember: ①,try()The class inside must be implemented AutoCloseable Interface. ②,stay try()Resources declared in code are implicitly declared as fianl. ③,Multiple resources can be declared using semicolon separation.
test
Create Lion.java:
package com.javapapers.exceptionhandling; public class Lion implements AutoCloseable { public Lion() { System.out.println("LION is OPEN in the wild."); }; public void hunt() throws Exception { throw new Exception("DeerNotFound says Lion!"); } public void close() throws Exception { System.out.println("LION is CLOSED in the cage."); throw new Exception("Unable to close the cage!"); } }
Create Tiger.java:
package com.javapapers.exceptionhandling; public class Tiger implements AutoCloseable { public Tiger() { System.out.println("TIGER is OPEN in the wild."); }; public void hunt() throws Exception { throw new Exception("DeerNotFound says Tiger!"); } public void close() throws Exception { System.out.println("TIGER is CLOSED in the cage."); } }
Create the test class TryWithResourcesExample.java:
package com.javapapers.exceptionhandling; public class TryWithResourcesExample { public static void main(String[] args) { try (Lion lion = new Lion(); Tiger tiger = new Tiger()) { lion.hunt(); tiger.hunt(); } catch (Exception e) { System.out.println(e); } finally { System.out.println("Finally."); } } }
Output for above example:
LION is OPEN in the wild. TIGER is OPEN in the wild. TIGER is CLOSED in the cage. LION is CLOSED in the cage. java.lang.Exception: DeerNotFound says Lion! Finally.