假设我有一段代码,它接收用户输入并将其存储为整数。当用户输入其他内容时,会抛出
伪代码:
NumberFormat
异常。但是,由于我知道这可能发生,但除了检查它然后重新运行输入序列之外,我没有理由做任何事情,因此在do-while
循环中放置try-catch
并使布尔变量成为控制变量,这样做是否可行?是否存在这种异常处理可能会对我产生不利影响的情况?伪代码:
Scanner scanner = new Scanner(System.in);
boolean inputMismatch;
int number;
do {
try {
System.out.println("Enter a number");
number = Integer.parseInt(scanner.nextLine());
inputMismatch = false;
} catch (NumberFormatException e) {
e.printStackTrace();
inputMismatch = true;
}
} while (inputMismatch);
file.exists()
来避免FileNotFoundExdception
)。然而,在你的情况下,没有这样的方法,所以捕获异常是合理的选择。 - Jiri TousekhasNextInt
和next
/nextLine
,而不是捕获异常,但这只是我的个人意见。 - Tom