在java中抛出异常,抛出然后继续错误

时间:2014-05-27 12:58:40

标签: java exception

这是我写的新异常类:

package Q1;

public class EqualException extends Exception {

    public EqualException()
    {
    }

    public EqualException(String message){
        super(message);
    }

}

这是try和catch:

public SortedPair(T first, T second){
    try{
        if(((Comparable <T>)first).compareTo(second)>0){
        this.bigNum = first;
                                                this.smallNum = second;
    }
    else if(((Comparable <T>)first).compareTo(second)<0){
        this.smallNum = first;
        this.bigNum = second;
    }
    else throw new EqualException("IllegalPair Exception");
    }
    catch(EqualException e){
        e.printStackTrace();
    }
}

这是发送给SortedPair构造函数的主要部分:

public class Main {

    public static void main(String[] args){
        int num1=0,num2=0;
        ArrayList<SortedPair> sotredPairsArray = new ArrayList<SortedPair>(); //List of sorted pairs
        Scanner scan = new Scanner(System.in);
        SortedPair sotredPair;

        System.out.println("Enter pairs of numbers");
        System.out.println("to finish enter 0 ");
        System.out.println("---------------------------------------");

        do{
            System.out.println("Enter First number in the pair: ");
            num1 = scan.nextInt();
            if(num1!=0){
                System.out.println("Enter Second number in the pair: ");
                num2 = scan.nextInt();
                sotredPair = new SortedPair(num1, num2);
                sotredPairsArray.add(sotredPair);
            }
            System.out.println("---------------------------------------");
        }while(num1!=0 && num2!=0);

我的问题是,为什么在异常后我没有立即停止运行,我在控制台中看到另外一条消息: “--------------------------------------- 在对中输入第一个数字: “

2 个答案:

答案 0 :(得分:0)

将SortedPair的构造函数更改为:

public SortedPair(T first, T second) throws EqualException {
        if (((Comparable<T>) first).compareTo(second) > 0) {
            this.bigNum = first;
            this.smallNum = second;
        } else if (((Comparable<T>) first).compareTo(second) < 0) {
            this.smallNum = first;
            this.bigNum = second;
        } else
            throw new EqualException("IllegalPair Exception");
}

并在主

中捕获异常

答案 1 :(得分:0)

以下是我(我想编译器)从您的代码中理解的内容:

  • 你有一个抛出异常的try块
  • 异常捕获在catch块中(仍在SortedPair构造函数中)
  • 您打印异常堆栈跟踪(我想您可以在控制台上看到它)
  • 并且在catch块之后继续按顺序继续(毕竟它是使用它)

因此,您的程序再显示一条消息是完全正常的。

如果你想在错误之后停止,你可以不在SortedPair构造函数中捕获Exception(既不尝试也不捕获块)或者在catch块中再次抛出它:

catch(EqualException e){
    e.printStackTrace();
    throw e;
}

但顺便说一下,为了记录目的捕获一个例外并将其再次扔进catch块中被认为是不好的做法:如果你无法解决它

相关问题