finally
block is a block of code that is always executed after the execution of a try
block, regardless of whether an exception occurs or not.
catch
block, the finally
block will still execute.
try
{
// risky code that may throw exception
}
catch (ExceptionClassType e)
{
// exception handling code
}
finally
{
// cleanup code (always executes)
}
public class FinallyDemo1
{
public static void main(String[] args)
{
try
{
System.out.println("Inside try block");
int data = 10 / 2; // no exception
System.out.println("Result: " + data);
}
catch (ArithmeticException e)
{
System.out.println("Exception caught: " + e);
}
finally
{
System.out.println("Finally block always executes");
}
System.out.println("Rest of the code...");
}
}
Inside try block Result: 5 Finally block always executes Rest of the code...
public class FinallyDemo2
{
public static void main(String[] args)
{
try
{
System.out.println("Inside try block");
int data = 10 / 0; // ArithmeticException
System.out.println("Result: " + data);
}
catch (ArithmeticException e)
{
System.out.println("Exception caught: " + e);
}
finally
{
System.out.println("Finally block always executes");
}
System.out.println("Rest of the code...");
}
}
Inside try block Exception caught: java.lang.ArithmeticException: / by zero Finally block always executes Rest of the code...
finally
block:
finally
block executes whether exception occurs or not.
return
statement inside the try
or catch
block.
public class FinallyDemo3
{
public static void main(String[] args)
{
System.out.println(m1());
}
static String m1()
{
try
{
System.out.println("Inside try");
return "Returning from try";
}
catch (Exception e)
{
return "Returning from catch";
}
finally
{
System.out.println("Finally block executed before return");
}
}
}
Inside try Finally block executed before return Returning from try
finally
block may not execute
System.exit(0)
before reaching finally
.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.