将异常错误消息打印到控制台

时间:2016-10-15 18:01:21

标签: java

在print()方法中调用getCurrent()方法时,我很难向控制台输出错误消息。另外,在我的getCurrent()方法中,编译器说我需要返回一个double。我不理解返回双重问题,不应该尝试catch块绕过对getCurrent()的调用。

getCurrent方法:

    public double getCurrent() throws IllegalStateException{
    //check if element
    try{
        if(isCurrent() == true){
            return data[cursor];
        }else{
            throw new IllegalStateException
            ("No Element");
        }//end check        
    }//end try
    catch(IllegalStateException e){
        //print error message to console
        System.out.println(e.getMessage());
    }//end catch        
}//end method

isCurrent()方法:

    public boolean isCurrent(){
    if(cursor < manyItems){
        return true;
    }else{
    return false;
    }
}//end method

print()方法:

    public void print(){
    double answer;
    System.out.println(" Capacity = " + data.length);
    System.out.println(" Length = " + manyItems);
    System.out.println(" Current Element = " + getCurrent());
    System.out.print("Elements: ");
    for(int i = 0; i < manyItems; i++){
        answer = data[i];
        System.out.print(answer + " ");
    }//end loop
    System.out.println(" ");
}//end method

主要方法(无法调整):

  DoubleArraySeq x = new DoubleArraySeq();
  System.out.println("sequence x is empty");
  x.print();
  System.out.println("Trying to get anything from x causes an exception\n");
  System.out.printf("%5.2f", x.getCurrent());

正确输出:

序列x为空

容量= 10

length = 0

没有元素

元素:

尝试从x获取任何内容会导致异常

1 个答案:

答案 0 :(得分:0)

public double getCurrent() throws IllegalStateException{
    //check if element
    try{
        if(isCurrent() == true){
            return data[cursor];
        }else{
            throw new IllegalStateException("No Element");
        }//end check        
    }//end try
    catch(IllegalStateException e){
        //print error message to console
        System.out.println(e.getMessage());
    }//end catch        
}//end method

你抓住自己的throws IllegalStateException。删除try{}catch(){}

public double getCurrent() throws IllegalStateException{
    //check if element
    if(isCurrent() == true){
        return data[cursor];
    }else{
        throw new IllegalStateException("No Element");
    }//end check      
}//end method

主要:

try{

    DoubleArraySeq x = new DoubleArraySeq();
    System.out.println("sequence x is empty");
    x.print();
    System.out.println("Trying to get anything from x causes an exception\n");
    System.out.printf("%5.2f", x.getCurrent());
}catch(IllegalStateException e){
    System.err.println("This exception produce because there is no element");
}