package Ricks;
import java.util.Scanner;
public class ExceptionHandlingExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
// Exception 1: Handling NumberFormatException
System.out.print("Enter an integer: ");
int num = Integer.parseInt(scanner.nextLine()); // Could throw NumberFormatException
// Exception 2: Handling ArithmeticException (division by zero)
System.out.print("Enter a divisor: ");
int divisor = Integer.parseInt(scanner.nextLine());
int result = num / divisor; // Could throw ArithmeticException
System.out.println("Result: " + result);
// Exception 3: Handling ArrayIndexOutOfBoundsException
int[] numbers = {1, 2, 3};
System.out.print("Enter an index to access (0-2): ");
int index = Integer.parseInt(scanner.nextLine());
System.out.println("Number at index: " + numbers[index]); // Could throw
ArrayIndexOutOfBoundsException
} catch (NumberFormatException e) {
System.out.println("Error: Invalid number format! Please enter a valid integer.");
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Index out of bounds! Choose between 0 and 2.");
} finally {
System.out.println("Execution completed.");
scanner.close();
}
}
}