Try, Catch, Finally
Try, Catch, Finally
import java.util.InputMismatchException;
import java.util.Scanner;
// Handling InputMismatchException
try {
System.out.print("Enter an integer: ");
int number = scanner.nextInt(); // Expects an integer
System.out.println("You entered: " + number);
} catch (InputMismatchException e) {
System.out.println("Caught InputMismatchException: Please enter a valid integer.");
} finally {
scanner.nextLine(); // Clear the buffer
System.out.println("Input process completed.");
}
// Handling ArithmeticException
try {
System.out.print("Enter a divisor: ");
int divisor = scanner.nextInt();
int result = 10 / divisor; // Division operation
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: Division by zero is not allowed.");
} finally {
System.out.println("Arithmetic operation attempted.");
}
// Handling ArrayIndexOutOfBoundsException
try {
int[] arr = {1, 2, 3};
System.out.print("Enter an array index (0-2): ");
int index = scanner.nextInt();
System.out.println("Array value at index " + index + ": " + arr[index]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: Index out of range.");
} finally {
System.out.println("Array access attempted.");
}
scanner.close();
}
}
Invalid inputs result
Divisor
Array