Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate try catch finally .

Java Code Example — Exception Handling Programs

ADVERTISEMENT

Java Program to demonstrate try catch finally .

Objective

Write a Java program to demonstrate the use of the try-catch-finally block.

Algorithm / Approach

  1. Prompt the user to enter an integer.
  2. In a try block, use Scanner.nextInt() to read the input.
  3. Write a catch (InputMismatchException e) block to handle cases where the user types letters or words instead of a number.
  4. Add a finally { ... } block that prints "Runs Always".
  5. Test the program by entering valid and invalid data.
Test.java
import java.util.*;
class Test {
 public static void main(String[] a)
 {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter a Num: ");
  try {
   int x = s.nextInt();
   System.out.print("Entered Num: "+x);
  }
  catch(InputMismatchException e) {
   System.out.println("Please Enter Valid");
  }
  finally {
   System.out.print("Runs Always");
  }
 }
}

Expected Output

Enter a Num: Alok
Please Enter Valid
Runs Always

Explanation of the Program

  • The finally block is a crucial part of exception handling. It contains code that MUST be executed, regardless of whether an exception occurred or not.
  • If the user types a valid integer, the try block finishes, the catch block is ignored, and the finally block runs.
  • If the user types letters, the try block fails, the catch block runs, and the finally block STILL runs.
  • It is primarily used in real-world applications to close resources like database connections or file streams to prevent memory leaks.

Complexity

Time Complexity O(1)
Space Complexity O(1)

Common Mistakes

  • Putting resource cleanup code inside the try block instead of the finally block. If an exception occurs before the cleanup line, the resource will remain permanently open.
ADVERTISEMENT