4

这是我第一次使用异常处理,所以要温柔。我有一个接受 ID 的简单 blob 类,id 必须在 30 到 50 之间,否则会引发异常。

public class Blob {
int id;

public Blob() {

}

public Blob(int id) throws Exception {
    this.id = id;
    if (id < 30 || id > 50)
        throw new Exception ("id = " +id+ ", must be between 30 and 50 inclusive");
}
}

它应该提示用户输入一个 id,如果它不在 30 到 50 之间,则抛出异常,并且应该继续,直到用户输入一个有效的输入,然后简单地显示 id 号。

public class BlobCreator {

public static void main(String[] args) {
    int id;
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter ID number: ");
    id = scan.nextInt();

    do {
        try {
            Blob b = new Blob(id);
        }

        catch (Exception e) {
            System.out.println(e);
        }
        System.out.println("Enter a different ID: ");
        id = scan.nextInt();
    }
    while(true);
    }   
System.out.println("Blob ID: " +id);
}

我认为我正确地使用了 throw 和 catch,但我的循环无法正常工作,所以我认为这应该是一个简单的修复,但我无法做到恰到好处。也正在使用 while 循环,就像我对这种情况有最好的方法,还是有更好的方法来循环 throw 和 catch?

感谢您的任何帮助

4

2 回答 2

7

您应该break;在代码成功执行之后放置。

do {
    try {
        Blob b = new Blob(id);
        break;
    }
    catch (Exception e) {
      System.out.println(e);
    }
    System.out.println("Enter a different ID: ");
    id = scan.nextInt();
} while(true);

因此,每次循环到达其主体的末尾时,它都会跳出循环。blob只有在成功创建后才应该中断。虽然我不明白你为什么要放一个break。循环可以检查输入的while输入是否有效并简单地停止循环。

while在一个do-while循环中修改了...通过使用true循环将永远运行,除非构造函数没有抛出异常...这使得代码更通用(如果你修改了blob构造的条件,你不会必须修改while循环的条件)。

于 2013-09-16T22:57:15.287 回答
2

抱歉,聚会有点晚了。希望最终来到这里的用户可能会发现这很有用。不鼓励使用break关键字 这是一个非常简单的实现,可以在实现重试机制后脱离它会在循环上迭代指定的次数,如果异常仍然存在,则抛出异常。这可以用于实际可能导致 IO/网络错误的实际现实场景,resttemplate并且可以在这些情况下重试

public class TestClass {

    public static void main(String[] args) throws Exception {

        try {
            int c = anotherM();
            System.out.println("Now the value is" + c);
        } catch (Exception e) {
            System.out.println("Inside" + e);
        }
    }

    public static int anotherM() throws Exception {
        int i = 4;
        Exception ex = null;
        while (i > 0) {
            try {
                System.out.println("print i" + i);

                throw new IOException();
                // return i;
            } catch (Exception e) {
                System.out.println(e);

                i--;
                if (i == 1) {
                    ex = new Exception("ttt");

                }

            }
        }
        if (ex != null) {
            throw new Exception("all new");
        } else {
            return i;
        }

    }

}
于 2019-05-29T08:43:54.640 回答