如何捕获NegativeArraySizeException?

时间:2014-07-17 07:09:00

标签: java

如何捕获给定数组中的NegativeArraySizeException。我想在给定数组中显示最大数字,但它显示NegativeArraySizeException

示例:

12, -23, 34 

TreeSet ts=new TreeSet(); 
public void abc() { 
    Scanner sc=new Scanner(System.in); 
    int s1=0; 
    System.out.println("enter number of elemtns "); 
    s1=sc.nextInt(); 
    int i[]=new int[s1]; 

    for(int i2=0; i2<=i.length; i2++) { 
        int s2=sc.nextInt(); 
        if(s2<0) 
            throw new NegativeArraySizeException(); 
        int i1[]=new int[s2]; 
        System.out.println("first,,,,"+s2); 
        ts.add(s2); 
        System.out.println("higest....."+ts.last()); 
    } 
}

public static void main(String[] args) { 
   StringAbc s=new StringAbc(); s.abc(); 
}

3 个答案:

答案 0 :(得分:2)

这样的东西?

int arrSize = -8;
try {
    int[] myArray = new int[arrSize];
} catch (NegativeArraySizeException ex) {
    System.out.println("Can't create array of negative size");
}

输出:Can't create array of negative size

答案 1 :(得分:2)

环绕try-catch块中的代码

StringAbc s=new StringAbc(); s.abc();  

try 
{
   StringAbc s=new StringAbc(); s.abc(); 
}
catch (NegativeArraySizeException ex) 
{
   System.out.println( ex.getMessage());
} 

答案 2 :(得分:0)

我的理解是你要实现这个

public void abc() {
  Scanner sc=new Scanner(System.in);
  int s1=0;
  System.out.println("enter number of elemtns ");

  //Read the size of array from user and check if it is not negative

  s1=sc.nextInt();
  if(s1<0) throw  new NegativeArraySizeException("Array size cannot be negative.");
  int i[]=new int[s1];
  int s2 = 0;
  for(int i2=0;i2<i.length;i2++) {
    System.out.println("Enter element");
    s2=sc.nextInt();

  //get input from user and dont allow negtive numbers in the array

    if(s2<0) throw new IllegalArgumentException("Negative numbers not allowed");
    ts.add(s2);
  }
  System.out.println("first,,,,"+s2);
  System.out.println("higest....."+ts.last());
 }