Exception finally


When the exception is thrown, instead of executing the execution in any way, all of a sudden, the nonlinear takes the path that changes the normal flow through the method. Depending on how the method is coded, an exception can return the method prematurely. This can be a problem in some ways. For example, if a method opens a file after logging in and closes it after exiting, you do not want the code to close the file and bypass the exception-handling method. The keyword "finally" was created to address this inconsistency.

"finally" creates a block of code that will be executed after the end of the try/catch block and before the code of the try/catch block to try. Whether the "finally" block has made an exception is effective. If an exception is thrown, the "end to end" block will be executed if the exception does not match any catch statement. Whenever a method is about to return to the caller from inside the try/catch block, except one or an explicit return statement, the "finally" clause is executed just before the method returns. It may be effective to close the file handles and release any other resources that may have been allocated at the beginning of the procedure to dispose of them before returning. The "finally" clause is correct. However, each attempt statement requires at least one catch or “finally” clause.

Program
// demonstrate finally block
class A{
void ShowA(){
 try{
  throw new RuntimeException("hello");
 }
 finally{
  System.out.println("ShowA() inside the finally block");
 }
}
void ShowB(){
 try{
  ShowA();
 }
 finally{
  System.out.println("ShowB() inside the finally block");
 }
}
void ShowC(){
 try{
  ShowB();
 }
 finally{
  System.out.println("ShowC() inside the finally block");
 }
}
}
public class Main {
  public static void main(String[] args) {
    A a1 = new A();
    try{
    a1.ShowC();
    }
    catch(RuntimeException re){
    System.out.println("Exception caught.");
    }
  }
}