1. Never return in a finally statement.
If you are in return a block then any finally s that Throwable aren ' t caught would be completely lost.
e.g.
1 //"done!" would be a print out, but there is no "Got it."2 Public classTest {3 Public Static voidMain (string[] args) {4 Try {5 dosomething ();6System.out.println ("done!");7}Catch(RuntimeException e) {8System.out.println ("Got it.");9 }Ten } One A Public Static voiddosomething () { - Try { - Throw Newruntimeexception (); the}finally { - return; - } - } +}
2. If return in try/catch, changes in finally would not affect return value.
finally Black run before return, but the return value would be copied.
1 //print "123"2 Public classTest {3 Public Static voidMain (string[] args) {4 System.out.println (getString ());5 }6 7 Public StaticString getString () {8String str = "123";9 Try {Ten Throw NewException (); One}Catch(Exception e) { A return str; -}finally { -str = "456"; the } - } -}
Java exception Handling (Exception handling)