Run the following code: public class BadArray { public static void main(String[]
ID: 3815974 • Letter: R
Question
Run the following code:
public class BadArray {
public static void main(String[] args) {
// Create an array with 3 elements.
int[] numbers = { 1, 2, 3 };
// Attempt to read beyond the bounds
// of the array.
for (int i = 0; i <= 3; i++)
System.out.println(numbers[i]);
}
}
1. What is the output of the program? If there is exception thrown, what is the name of the exception ( or Class name)? Is it Checked or Unchecked Exceptions?
2. Now write try and catch block in your code to handle exception. The ExceptionType in the catch block should be same exception you found in question# 1.
3. What other class name you can use as ExceptionType
try {
(try block statements...)
} Catch (ExceptionType ParameterName)
{ (catch block statements…)
}
Sample Output:
1
2
3
You can't print more than 3 items
Explanation / Answer
1. What is the output of the program? If there is exception thrown, what is the name of the exception ( or Class name)? Is it Checked or Unchecked Exceptions?
Ans:
1
2
3
Yes, java.lang.ArrayIndexOutOfBoundsException: has been thrown. It is uncheck exception
3. What other class name you can use as ExceptionType
Ans: ArrayIndexOutOfBoundsException
2)
public class BadArray {
public static void main(String[] args) {
// Create an array with 3 elements.
int[] numbers = { 1, 2, 3 };
// Attempt to read beyond the bounds
// of the array.
try {
for (int i = 0; i <= 3; i++)
System.out.println(numbers[i]);
} catch (ArrayIndexOutOfBoundsException ex)
{
System.out.println("You can't print more than 3 items");
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.