try{
output.format("%d %s %s %.2f%n", input.nextInt(),
input.next(),input.next(),input.nextDouble());
} catch(FormatterClosedException formatterClosedException){
System.err.println("Error writing to file. Terminating.");
break;
} catch(NoSuchElementException noSuchElementException){
System.err.println("Invalid input. Please try again.");
input.nextLine();
}
的方法format(String format, Object... args)
在Formatter
类投2 exception
:IllegalFormatException
和FormatterClosedException
,但在我的书上面的代码捕获NoSuchElementException
和FormatterClosedException
。我应该捕获一个方法抛出的所有异常吗?
- 为什么代码捕获
NoSuchElementException
,但没赶上IllegalFormatException
? - 我们如何知道如果我们需要赶上
NoSuchElementException
如果甚至没有在在线documentation的格式化程序类format()方法中说明?
试穿例外阅读的话题,例如:http://stackoverflow.com/questions/7586305/how-to-know-which-exception-is-thrown – usman
[阅读此](https://docs.oracle.com/javase/7/docs/api/java/util/NoSuchElementException.html)你会明白NoSuchElementException –
我给你在答案的最后解释。这是'Scanner'谁可以抛出'NoSuchElementException'。 – xenteros