Page 171 - CTS - CSA TP - Volume 2
P. 171
COMPUTER SOFTWARE APPLICATION - CITS
2 ArrayIndexOutOfBoundsException:
• Description: Occurs when attempting to access an array element with an index outside the array’s bounds.
• Handling Approach: Ensure the index is within the array’s bounds.
public class ArrayIndexOutOfBoundsExceptionExample {
public static void main(String[] args) {
try {
int[] arr = {1, 2, 3};
int element = arr[5]; // This will throw an ArrayIndexOutOfBoundsException
System.out.println(“Element at index 5: “ + element);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(“Caught ArrayIndexOutOfBoundsException: “ + e.getMessage());
}
}
}
Output:
3 ArithmeticException:
• Description: Occurs when an arithmetic operation results in an undefined mathematical result (e.g., division
by zero).
• Handling Approach: Check for conditions that might lead to undefined results.
public class ArithmeticExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw an ArithmeticException
System.out.println(“Result of division: “ + result);
} catch (ArithmeticException e) {
System.out.println(“Caught ArithmeticException: “ + e.getMessage());
}
}
}
Output:
156
CITS : IT & ITES - Computer Software Application - Exercise 106