The following code causes an exception error: import java.io.BufferedReader; imp
ID: 3803790 • 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));
}
}
Starting with this provided code, add the following functionality:
1) Use a Try/Catch block so that the exception is caught and the program exits a bit more gracefully
Explanation / Answer
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 {
try
{
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));
}
catch(Exception e)
{
System.out.println("Index out of bound excetion");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.