Commit dc5f8171 authored by Bhargavi Ghanta's avatar Bhargavi Ghanta

️ Completed Task 3: Modified program with try-with-resources and InvalidAgeException

parent bb573060
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class AgeValidaator {
// Method to validate age
public static void validateAge(int age) {
if (age <= 0) {
throw new InvalidAgeException("Invalid age: Age must be greater than 0.");
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Try-with-resources block to auto-close FileWriter
try (FileWriter writer = new FileWriter("age_output.txt")) {
System.out.print("Enter your age: ");
int age = scanner.nextInt();
try {
validateAge(age);
writer.write("Valid age entered: " + age);
System.out.println("Age is valid. Written to file.");
} catch (InvalidAgeException e) {
writer.write("Error: " + e.getMessage());
System.out.println("Exception: " + e.getMessage());
}
} catch (IOException e) {
System.out.println("File operation error: " + e.getMessage());
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment