带有异常处理的while循环

4

这是我第一次使用异常处理,所以请温柔点。我有一个简单的Blob类,它接受一个ID,该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,如果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?
感谢您所有的帮助。
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后才中断。虽然我不明白为什么您要放一个breakwhile循环可以检查输入是否有效并简单地停止循环。
我将while修改为do-while循环... 通过使用true,循环将永远运行,除非构造函数未抛出任何异常... 这使得代码更加通用(如果您修改了blob-construction的条件,则不必修改while循环的条件)。

是的,当我用这种方式时也遇到了同样的问题。 - user2745043
哪一个?是在catch块中的还是在底部的?它们应该是可达的... - Willem Van Onsem
底部那个,但我已经解决了这个问题,它是可达的,但我仍然得到一个(在此标记后预期出现“println”,=的语法错误)??? - user2745043
你能否在问题中发布整个代码...在Java中,发布的代码似乎可以在我的机器上运行:S。 - Willem Van Onsem
我已经更新了代码,现在的代码看起来很好,除了println这个函数。 - user2745043
显示剩余9条评论

2
抱歉,我来晚了。希望到达这里的用户会发现这很有用。 不鼓励使用break关键字。 这是一个非常简单的实现,在实现重试机制后立即中断。 这将在指定次数内循环迭代,并且如果异常仍然存在,则抛出异常。这可以用于实际的场景,例如resttemplate可能会导致IO/网络错误,在这些情况下可以进行重试。
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;
        }

    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接