/创建一个方法callMethod,其中显示数组列表中的所有国家,如果超过5个国家,该方法将向main()方法抛出异常/
导入java.util.Arrays;
导入java.util.List;
导入java.util.ListIterator;
公共(public)类别国家{
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");
}
}
}
最佳答案
用类似的东西定义你的方法
public void callMethod() {
if (null!=country && country.size() > 5) {
throw new RuntimeException("Maximum countries allowed are 5");
}
}
您可以通过使用 try{...}catch(){} 包装
callMethod
调用来捕获错误
try {
countries.callMethod();
} catch (RuntimeException rex) {
rex.printStackTrace();
}
关于java - 如何向由 arraylist 组成的 main 方法抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61832473/