The function of "finally"Resource leaks:when a resource is no longer used by an application, but thisthis happens when the program does not declare to the system that the resource is no longer being usedfinallystatement blocks are primarily used to address resource disclosure issues, which are located inCatchstatement block,JVMensure that they must be executed. Note:finallyAn exception can also occur in a statement block ifthis happens and the previous exception is discarded.
Sample program:
Public classembededfinally { Public Static voidMain (String args[]) {intresult; Try{System.out.println ("In Level 1"); Try{System.out.println ("In Level 2"); //result=100/0; //Level 2 Try{System.out.println ("In Level 3"); Result=100/0;//Level 3 } Catch(Exception e) {System.out.println ("Level 3:" +E.getclass (). toString ()); } finally{System.out.println ("In Level 3 finally"); } //result=100/0; //Level 2 } Catch(Exception e) {System.out.println ("Level 2:" +E.getclass (). toString ()); } finally{System.out.println ("In Level 2 finally"); } //result = 100/0; //Level 1 } Catch(Exception e) {System.out.println ("Level 1:" +E.getclass (). toString ()); } finally{System.out.println ("In Level 1 finally"); } }}
Results:
Analysis:
when there are multiple nested Try ... .. Catch ... .. finally , pay special attention to finally time of execution.
Special attention:
when there are multiple layers of nestedfinally, exceptions are thrown at different levels, thrown at different locations, may lead to differentfinallylanguagesentence block execution order. Sample Program 2
Public classsystemexitandfinally { Public Static voidMain (string[] args) {Try{System.out.println ("In Main"); Throw NewException ("Exception is thrown in main"); //system.exit (0); } Catch(Exception e) {System.out.println (E.getmessage ()); System.exit (0); } finally{System.out.println ("In finally"); } }}
Results:
Java Exception Handling finally usage