Java Program to demonstrate try catch finally .
Objective
Write a Java program to demonstrate the use of the try-catch-finally block.
Algorithm / Approach
- Prompt the user to enter an integer.
- In a
tryblock, useScanner.nextInt()to read the input. - Write a
catch (InputMismatchException e)block to handle cases where the user types letters or words instead of a number. - Add a
finally { ... }block that prints "Runs Always". - 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
finallyblock 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
tryblock finishes, thecatchblock is ignored, and thefinallyblock runs. - If the user types letters, the
tryblock fails, thecatchblock runs, and thefinallyblock 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
tryblock instead of thefinallyblock. If an exception occurs before the cleanup line, the resource will remain permanently open.