抓住了Java异常,但又自动抛出了?

时间:2012-10-07 08:52:09

标签: java exception exception-handling

对于学校我正在创建一个简单的几何程序,询问角的数量和形状的坐标。为了防止错误输入(即字符而不是整数),我想我会使用异常处理。它似乎工作正常,但一旦我输入错误,它会捕获错误并设置一些默认值。它应该继续要求更多的输入,但不知何故,这些最终会在不要求新输入的情况下捕获相同的异常。

public static void main(String[] args) {
   Scanner stdin = new Scanner(System.in);

    try {
        int hoeken;
        System.out.print("How many corners does your shape have? ");

        try {
            hoeken = stdin.nextInt();
            if(hoeken < 3) throw new InputMismatchException("Invalid side count.");
        }
        catch(InputMismatchException eVlakken){
            System.out.println("Wrong input. Triangle is being created");
            hoeken = 3;
        }

        Veelhoek vh = new Veelhoek(hoeken);
        int x = 0, y = 0;

        System.out.println("Input the coordinates of your shape.");
        for(int i = 0; i < hoeken; i++){
            System.out.println("Corner "+(i+1));                
            try {
                System.out.print("X: ");
                x = stdin.nextInt();
                System.out.print("Y: ");
                y = stdin.nextInt();                    
            } catch(InputMismatchException eHoek){
                x = 0;
                y = 0;
                System.out.println("Wrong input. Autoset coordinates to 0, 0");
            }                
            vh.setPunt(i, new Punt(x, y));
        }

        vh.print();

        System.out.println("How may points does your shape needs to be shifted?");
        try {
            System.out.print("X: ");
            x = stdin.nextInt();
            System.out.print("Y: ");
            y = stdin.nextInt();

        } catch(InputMismatchException eShift){
            System.out.println("Wrong input. Shape is being shifted by 5 points each direction.");
            x = 5;
            y = 5;
        }            

        vh.verschuif(x, y);
        vh.print();

    } catch(Exception e){
        System.out.println("Unknown error occurred. "+e.toString());
    } 
}

因此,如果用户通过尝试创建具有2个边的形状或输入char而不是整数来启动,则会生成InputMismatchException并处理它。然后它应该通过询问角点的坐标来继续程序,但是它会不断地抛出新的异常和句柄。

出了什么问题?

1 个答案:

答案 0 :(得分:2)

根据我的API,您需要跳过错误输入以获取下一个。 “当扫描程序抛出InputMismatchException时,扫描程序将不会传递导致异常的标记,因此可以通过其他方法检索或跳过它。”

获取异常后调用skip()方法应解决此问题。 http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

相关问题