Lab 3 (Computer Programming 2) Tapil
Lab 3 (Computer Programming 2) Tapil
BSIT-A201
Code:
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;
// ArithmeticException
try {
System.out.print("Enter numerator: ");
int num = scanner.nextInt();
System.out.print("Enter denominator: ");
int denom = scanner.nextInt();
System.out.println("Result: " + (num / denom));
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}
// IndexOutOfBoundsException
try {
int[] numbers = {1, 2, 3};
System.out.print("Enter an index (0-2): ");
int index = scanner.nextInt();
System.out.println("Array value: " + numbers[index]);
} catch (IndexOutOfBoundsException e) {
System.out.println("Error: The specified index is out of bounds.");
}
// InputMismatchException
try {
System.out.print("Enter an integer: ");
int value = scanner.nextInt();
System.out.println("You entered: " + value);
} catch (InputMismatchException e) {
System.out.println("Error: Invalid input. Please enter a valid
integer.");
scanner.next();
}
// NoSuchElementException
try {
scanner.nextLine();
System.out.print("Enter a word: ");
String text = scanner.next();
System.out.println("You entered: " + text);
} catch (NoSuchElementException e) {
System.out.println("Error: No input detected. Please provide a valid
input.");
}
// ArrayIndexOutOfBoundsException
try {
int[] array = new int[3];
array[5] = 10;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Array index is out of range.");
}
System.out.println("Program completed.");
scanner.close();
}
}
Sample Output: