Finally block in java

Finally block in java

Finally block contains code which are need to be excetued regardless where the exception is hrown ocuurs in try block or not. This blcok is used to exceite some block of code after try-catch block.

Syntax of Finally Block

try {
//Statements that may cause an exception
}
catch {
//Handling exception
}
finally {
//Statements to be executed,regardless exceptions
}

Example for final blcok

class Main {
public static void main(String[] args) {
try {
int dividebyzero = 25 / 0;
} catch (ArithmeticException e) {
System.out.println(e);
} finally {
System.out.println("Finally block is always executed");
}
}
}

Output

java.lang.ArithmeticException: / by zero
Finally block is always executed

In the above program ,there is an exception of ArithmeticException, then controller exceutes the final block, so last output will be “Finally block is always executed”

Some Key Points about finally block

  • Finally, the block cannot be declared without the try block. important block of code which should be excited is placed inside the final block
  • For each try block, there can be only one finally block
  • If there is an exception in the try block, then finally block will be executed after the catch block, if there is no exception then finally block will be executed after the try block
  • finally block is not mandatory, there can be a try-catch block without the finally block
Last updated on by vishal devxo