Exception handling Java exception handling model in contrast to other languages, the keyword finally is the most outstanding new feature. The finally widget makes the code in the section always execute, regardless of whether an exception occurs, especially for maintaining the internal state of the object (used to ensure that the exception is in a valid state for recovering the object). To ensure that the program will automatically run again after processing the exception and to clean up non-memory resources (resources that the garbage collection mechanism cannot handle, such as database connections, sockets, and so on).
One thing to note, though, is to try not to return from the try section (call back) because as long as a finally section exists, it is bound to be executed, and if you call a return statement in the finally section, the returned value in the Try section is obscured. So that the method caller gets the return value in the finally section-which is often the original intention of the program writing.
For a simple example:
Class Finallytest
{
public int Mothoda ()
{
try {
return;
}finally {
return 20;
}
}
public static void Main (string[] args) {
Finallytest ft=new finallytest ();
int x= Ft.mothoda ();
System.out.println ("The value of X is:" +x);
}
}
To run the code above, we find that the returned value is 20 in the finally section, not 10 in the try section.
Programmers traditionally assume that when they execute a return statement, they immediately leave the function in execution and go back to the method call. But in the Java language, this view is no longer the golden rule once the finally section appears. --"Practical Java"
To circumvent this potential pitfall, we need to try not to call return-break or continue statements in the try section, and they all have the potential to get the program into the Finall section. If this is unavoidable, then we must ensure that the code in the finally section does not affect the return value of the function.