Finally summary:
Finally code block: Defines code that must be executed
Typically used to close resources or some code that must be executed
Example 1:finally function Demo
classFushuexceptionextendsexception{fushuexception (String m) {Super(m); }}classDemo { Public intDivintXintYthrowsfushuexception {if(y<0) { Throw NewFushuexception ("Divisor is negative"); } returnx/y; }}classexceptiondemo1{ Public Static voidMain (String args[]) {Demo d=NewDemo (); Try { intX=d.div (4,-1); System.out.println ("X=" +x); } Catch(fushuexception e) {System.out.println (e.tostring ()); } finally{System.out.println ("Finally");//Finally, the code that is bound to be executed} System.out.println ("Over"); }}
Operation Result:
Fushuexception: Divisor is negative
Finally
Over
Example 2:
1 classFushuexceptionextendsException2 {3 fushuexception (String m)4 {5 Super(m);6 }7 }8 9 Ten classDemo One { A Public intDivintXintYthrowsfushuexception - { - if(y<0) the { - Throw NewFushuexception ("Divisor is negative"); - } - returnx/y; + } - } + A at classExceptionDemo1 - { - Public Static voidMain (String args[]) - { -Demo d=NewDemo (); - Try in { - intX=d.div (4,-1); toSystem.out.println ("x=" +x); + } - Catch(fushuexception e) the { * System.out.println (e.tostring ()); $ return;Panax Notoginseng } - finally the { +System.out.println ("finally");//Finally, the code that is bound to be executed A } theSystem.out.println ("Over"); + } -}
Operation Result:
Fushuexception: Divisor is negative
Finally
The use of exception handling mechanism _finally in Java