The following code causes an exception error: import java.io.BufferedReader; imp
ID: 663869 • Letter: T
Question
The following code causes an exception error:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Ex02 {
public static void main(String[] args) throws IOException {
BufferedReader userInput = new BufferedReader
(new InputStreamReader(System.in));
ArrayList<String> myArr = new ArrayList<String>();
myArr.add("Zero");
myArr.add("One");
myArr.add("Two");
myArr.add("Three");
System.out.println(myArr.get(4));
}
}
How do I use a Try/Catch block so that the exception is caught and the program exits a bit more gracefully. Starting with the provided code again (without the Try/Catch block), what needs to be done to fix the code so that it runs correctly. That is to say, it should display the last item in the ArrayList.
Explanation / Answer
Since the element that you intend to print is not defined, it will throw the IndexOutOfBoundsException. Enclose the following code snippet in a try block:
System.out.println(myArr.get(4));
In the catch block, write the following code snippet to display the last element of the arraylist:
System.out.println(myArr.get(myArr.size() -1));
Final code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Ex02
{
public static void main(String[] args) throws IOException {
BufferedReader userInput = new BufferedReader (new InputStreamReader(System.in));
ArrayList<String> myArr = new ArrayList<String>();
myArr.add("Zero");
myArr.add("One");
myArr.add("Two");
myArr.add("Three");
try
{
System.out.println(myArr.get(4));
}
catch(IndexOutOfBoundsException e)
{
System.out.println("Will cause exception since you are accessing undefined position in the arraylist ");
System.out.println("Printing the last element in the array list ");
System.out.println(myArr.get(myArr.size() -1));
}
}
}
Output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.