需要帮助捕获异常

时间:2012-10-25 06:40:49

标签: java generics exception-handling

我正在创建一个用于整数的通用Pair类。

异常类:

public class WrongThing extends Exception{
    public WrongThing(String message) {
        super(message);
    }
}

主要课程:

public class Pair<E> implements Comparable<E>{
    private E var1;
    private E var2;
    public Pair(E var1, E var2) throws WrongThing{
        //this is on purpose!!!
        System.out.println("var1 and var2 are switched");
        this.var1 = var2;
        this.var2 = var1;
    }

    void get(){
        System.out.println("the first actualy 2nd: "+
                var1 + "the ");
                System.out.println("  second actualy first" + var2);
    }

    void set1(E temp){
        System.out.println("var1 and var2 are switched");
        temp = var1;
    }

    void set2(E temp){
        System.out.println("var1 and var2 are switched");
        temp = var2;
    }

    E smallest(E var1, E var2){

        return var1;
    }

    @Override
    public int compareTo(Object arg0) {
        // TODO Auto-generated method stub
        return 0;
    }
}

测试用例

import java.util.Scanner;
import java.util.InputMismatchException;

public class PairTest {
    public static void main(String[] args) throws WrongThing{
        System.out.println("two integers please");
        Scanner sc = new Scanner(System.in);
        Pair<Integer> newPair;
        Pair<Integer> tempPair1= new Pair<Integer>(3,2);

        try{
            newPair = new Pair<Integer>(sc.nextInt(),sc.nextInt());
            //throw new InputMismatchException("that is not an Integer....");
        }catch(WrongThing exception){
            //System.out.println("you cant do that. try again and press enter after the first integer");
            newPair = new Pair<Integer>(sc.nextInt(),sc.nextInt());
            newPair.get();

        }
        finally{


        }
    }
    //newPair = new Pair<Integer>(sc.nextInt(),sc.nextInt());
}

当我运行此代码时,我得到InputMismatchException。我没有正确地创建我的异常或者在抛出它时没有捕获它吗?

6 个答案:

答案 0 :(得分:1)

除非我遗漏某些内容,否则您似乎只是试图抓住WrongThing例外,而不是InputMismatchEception

try{
    // ...
}catch(WrongThing exception){
    // ...
}

答案 1 :(得分:1)

WrongThing是您的自定义例外。必要时你需要扔它并抓住它。

try{
    // throw new WrongThing("wrong thing");
}catch(WrongThing e1){
    // ...
}catch(InputMismatchException e2){
    // ...
}
sc.nextInt()方法InputMismatchException引发

if the next token does not match the Integer regular expression, or is out of range。所以你也需要慢慢来。

答案 2 :(得分:0)

对于Scanner类,您必须遵循流程hasNext() - &gt;下一个()

你不会以这种方式得到任何例外。

   Scanner sc = new Scanner(System.in);       
          while (sc.hasNext()) {

                 if(sc.hasNextInt())
                System.out.println(sc.nextInt());

              sc.next();
          }
         sc.close();

另一件事是在底部有一个带有catch(Exception e)的级联异常块,以确保捕获所有异常。

   try{
         // code which throws checked exceptions.
        }catch(WrongThing e1){      
            e1.printStackTrace();
        }catch(Exception e2){
            e2.printStackTrace();
        }finally{
           // cleanup
       }

答案 3 :(得分:0)

java.util.InputMismatchException的文档说:

  

Scanner抛出,表示检索到的令牌与预期类型的​​模式不匹配,或者令牌超出预期类型的​​范围。

Scanner.nextInt()的那个说:

  

抛出:InputMismatchException - 如果下一个标记与Integer正则表达式不匹配,或者超出范围

基本上,当您在控制台中输入非整数的内容时,会从Scanner.nextInt()抛出异常。当发生这种情况时,甚至不会调用构造函数new Pair<Integer>(...),因此将它放在构造函数中的任何检查都变得无用。

您需要做的是

newPair = null;
while (newPair == null) {
    try {
        newPair = new Pair<Integer>(sc.nextInt(),sc.nextInt());
    } catch(InputMismatchException exception){
        System.out.println("you cant do that. try again and press enter after the first");              
    }
}

答案 4 :(得分:0)

创建对类

的对象时
Pair newPair = new Pair<Integer>(sc.nextInt(),sc.nextInt());

它只能抛出自定义异常,因为您在类中提到过这种类型的异常。期望sc.nextInt()来自控制台的Integer类型的输入,当传递任何其他字符时,它会抛出InputMismatchException。所以你还需要捕获像

这样的InputMismatch Exception
try{
    // throw new WrongThing("wrong thing");
}catch(WrongThing e1){
    // ...
}catch(InputMismatchException e2){
    // ...
}

答案 5 :(得分:0)

扫描程序正在抛出您未处理的InputMismatchException。 InputMismatchException是一个RuntimeException,因此您不需要显式捕获它。 (通常是程序员错误)如果您使用的是Java 7,则可以使用此语法(multicatch)来处理多个异常

try{
....
}
catch(WrongThing|InputMismatchException e1){
        //deal with exception.
}

这假设您希望以相同的方式处理这两个异常。如果你不这样做,我会建议将它们分开,因为其他答案已经明确了。