引发异常后如何循环程序

时间:2019-03-11 00:36:36

标签: java exception

我有以下代码可能会引发异常:

import java.util.*;
import java.io.*;

class Test {
    public static void main (String [] args) {
        try {
            Scanner keyboard = new Scanner (System.in);
            int n1, n2;
            System.out.print("Type an int: ");
            n1 = keyboard.nextInt();
            System.out.print("Type another int: ");
            n2 = keyboard.nextInt();
            int r = n1/n2;
        }
        catch (ArithmeticException e) {
            System.out.println("Divide by 0");


        }
        catch (InputMismatchException e) {
            System.out.println("Wrong entry");
        }
    }
}

引发异常后。我希望程序返回要求用户再次输入新int而不是退出。

4 个答案:

答案 0 :(得分:3)

while (true)包裹代码,并在break块的末尾添加一个try,以便仅在不引发异常的情况下才可以到达它。

例如

while (true) {

    try {

        // your code goes here ....

        break;    // this will only be reached if no exceptions thrown
    }
    catch (...) { 

    }
};  // close the while loop

// this will be reached after the break only, i.e. no exceptions

答案 1 :(得分:1)

我会使用infinite loop。准备就绪后,可以使用break语句退出它。

public static void main(String[] args) {
        while (true) {
            try {
                @SuppressWarnings("resource")
                Scanner keyboard = new Scanner(System.in);
                int n1, n2;
                System.out.print("Type an int: ");
                n1 = keyboard.nextInt();
                System.out.print("Type another int: ");
                n2 = keyboard.nextInt();
                int r = n1 / n2;
                //Do whatever... use 'break' to exit the loop when you are done
            } catch (ArithmeticException e) {
                System.out.println("Divide by 0");

            } catch (InputMismatchException e) {
                System.out.println("Wrong entry");
            }
        }
    }

答案 2 :(得分:1)

while (true) {

    try {

        // your code

        break;
    }
    catch (Exception e) { 

    }
}; 

答案 3 :(得分:0)

我不喜欢“ while(true)with a break”的成语。在这种情况下,我发现更清楚了-我很少有适用于所有情况的规则-引入了控制循环的辅助变量。

boolean repeat;
do {
    repeat = false;
    try {  
        ...stuff...
    }
    catch (SomeException ex) {
        ... error stuff...
        repeat = true;
    }
while (repeat);

这是(a)使循环终止比循环外的任意跳转('break')更清晰,并且(b)当发现有其他原因需要重新进行循环主体时,使其变得微不足道。

>