我想知道如何抓住我已经分开捕获的两个例外情况?
private static boolean checkParameters(Scanner scnr) {
boolean result = true;
return result;
}
private static MnthInYear createMonthInYear() throws IllegalArgumentException {
String a = JOptionPane.showInputDialog(null, "Enter month and year");
Scanner sc = new Scanner(a);
MnthInYear obj = null;
if (checkParameters(sc)) {
try {
obj = new MnthInYear(sc.next(), sc.nextInt());
} catch (IllegalArgumentException exc) {
JOptionPane.showMessageDialog(null,"Wrong month!");
} catch (InputMismatchException exc2) {
JOptionPane.showMessageDialog(null,"Wrong year!");
} catch (NoSuchElementException exc3) {
JOptionPane.showMessageDialog(null,"No data!");
}
sc.close();
}
return obj;
}
我需要做这样的事情:
} catch (IllegalArgumentException AND InputMismatchException) {
JOptionPane.showMessageDialog(null,"Wrong month and year!");
}
我怎么能得到这个?
答案 0 :(得分:1)
使用此示例
为此:
catch (IOException ex) {
logger.log(ex);
throw ex;
catch (SQLException ex) {
logger.log(ex);
throw ex;
}
使用此:
catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
访问http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html
答案 1 :(得分:1)
从技术上讲,不,你不能这样做。一旦抛出一个异常,控制就会移动到相关的catch
块,而下一个块将不会被抛出。您可能想要的是实现验证模式,您可以在其中验证输入,使用输入聚合任何错误,然后在验证结束时使用单个消息对其进行汇总。
答案 2 :(得分:0)
如果有人对此感兴趣,我终于找到了解决方案。
private static boolean checkParameters(Scanner scnr) {
boolean result = true;
String msgError = "Invalid";
try {
month = scnr.next();
mnth = MnthInYear.Month.valueOf(month);//class MnthInYear defines enum Month
} catch (IllegalArgumentException exc) {
msgError += "month!";
result = false;
}
try {
year = scnr.nextInt();
if (year < 0) {
msgError += "year!";
result = false;
}
} catch (InputMismatchException exc) {
msgError += "month and year!";
result = false;
}
if (msgError != "") {
JOptionPane.showMessageDialog(null,msgError);
}
return result;
}
&#13;
感谢您的回答!