/Create a method namely callMethod in which display all countries from the arraylist,If more than 5 countries,the method will throw an exception to the main() method/
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;
public class Countries {
JavaScript
x
static List<String> country = Arrays.asList("Singapore", "America", "France","Japan","China","UK","Indonesia","India");
public static void main(String[] args) {
ListIterator<String> myListIterator = country.listIterator();
while (myListIterator.hasNext()) {
System.out.print(myListIterator.next() + " ");
}
System.out.println();
Countries countries = new Countries();
countries.callMethod();
}
public void callMethod() {
try {
System.out.println(country.get(6));
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Maximum countries is 5");
}
}
}
Advertisement
Answer
Define your method with something like
JavaScript
public void callMethod() {
if (null!=country && country.size() > 5) {
throw new RuntimeException("Maximum countries allowed are 5");
}
}
you can catch the error by wrapping callMethod
invocation call with try{...}catch(){}
JavaScript
try {
countries.callMethod();
} catch (RuntimeException rex) {
rex.printStackTrace();
}