//自定义异常类 public class ArrayElement extends Exception { public static final int MAX_NUM = 1000 ; private static final String MESSAGE = "集合存储元素过多" ; public ArrayElement (){ } public String getMessage (){ return MES
public class ArrayElement extends Exception{
public static final int MAX_NUM=1000;
private static final String MESSAGE="集合存储元素过多";
public ArrayElement(){
}
public String getMessage(){
return MESSAGE+"最大元素限制为"+MAX_NUM;
}
public void printStackTrace(){
System.err.println(MESSAGE);
super.printStackTrace();
}
}定义
import java.util.ArrayList;
import java.util.List;
public class UseArray {
public List<String> StoreElement(int size) throws ArrayElement{
List<String> list=new ArrayList<>( );
for(int i=0;i<size;i++){
if(i>ArrayElement.MAX_NUM)
throw new ArrayElement();
list.add("元素"+i);
}
return list;
}
}测试类
import java.util.List;
//自定义异常
public class test84 {
public static void main(String[] args){
UseArray uaet=new UseArray();
try {
List<String> list =uaet.StoreElement( 1100 );
System.out.println( list.size() );
}catch (ArrayElement e){
System.out.println( e.getMessage() );
e.printStackTrace();
}
}
}
运行结果