这是我第一次使用异常处理,所以请温柔点。我有一个简单的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?
感谢您所有的帮助。