Last time we looked at throwing and catching exceptions. In this lesson we will learn another keyword: finally

Finally is not the same as final. Final declares constants. Finally handles exceptions.

Finally the grammar:

try{

Code that may contain exceptions

}catch(exception class variable name){

Exception handling code

}… More than (catch)

finally{

Post-processing code

}

Let’s take a quick example:

Demo:

public static void main(String[] args) { try { test(); } catch (Exception e) { e.printStackTrace(); } } public static void test() throws Exception { try { throw new Exception("lalalala"); }catch (RuntimeException e){ e.printStackTrace(); }finally { System.out.println("finally"); }}Copy the code

Output:

finally

java.lang.Exception: lalalala

at helloworld.exception.FinallyTeach.test(FinallyTeach.java:15)

at helloworld.exception.FinallyTeach.main(FinallyTeach.java:7)

Conclusion:

If the exception is not caught, finally code is executed

Demo 2:

public static void main(String[] args) { try { test2(); } catch (Exception e) { e.printStackTrace(); } } public static void test2() throws Exception { try { throw new RuntimeException("abcd"); }catch (RuntimeException e){ e.printStackTrace(); }finally { System.out.println("finally"); }}Copy the code

Output:

finally

java.lang.RuntimeException: abcd

at helloworld.exception.FinallyTeach.test2(FinallyTeach.java:25)

at helloworld.exception.FinallyTeach.main(FinallyTeach.java:7)

Conclusion: If an exception is caught, the code in finally is still executed

Final Conclusion:

  1. Finally’s code must be executed whether or not the exception is caught.
  2. Finally is a good place to store code for releasing resources and subsequent processing