Answers for "finally in java"

1

importance of finally over return statement

finally block is more important than return statement when both are present 
in a program. For example if there is any return statement present inside 
try or catch block , and finally block is also present first finally statement 
will be executed and then return statement will be considered.
Posted by: Guest on December-01-2020
1

importance of finally block in java

Finally block is used for cleaning up of resources such as closing connections, 
sockets etc. if try block executes with no exceptions then finally is called 
after try block without executing catch block. If there is exception thrown in 
try block finally block executes immediately after catch block.
If an exception is thrown,finally block will be executed even if 
the no catch block handles the exception.
Posted by: Guest on December-01-2020
0

Java Finally Block

//The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception.

Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.

A finally block appears at the end of the catch blocks and has the following syntax 

try {
   // Protected code
} catch (ExceptionType1 e1) {
   // Catch block
} catch (ExceptionType2 e2) {
   // Catch block
} catch (ExceptionType3 e3) {
   // Catch block
}finally {
   // The finally block always executes.
}
Example
public class ExcepTest {

   public static void main(String args[]) {
      int a[] = new int[2]; // Size 2
      try {
         System.out.println("Access element three :" + a[3]); // Accessing 3rd element
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Exception thrown  :" + e);
      }finally { // Always executed no matter what!
         a[0] = 6;
         System.out.println("First element value: " + a[0]);
         System.out.println("The finally statement is executed");
      }
   }
}
Output : 
Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
Posted by: Guest on August-31-2021
0

finally keyword

It come after try catch block
A finally block of code always executes,
whether or not an exception has occurred.
Posted by: Guest on January-05-2021

Browse Popular Code Answers by Language