我正在使用HashMap并尝试生成DuplicateKeyException以防止覆盖现有密钥。
我试图根据某些用户输入抛出此异常,但是收到异常已经被捕获错误。
try {
Student student = map.get(uid); // uid is a user defined input.
if (student != null) { // test for key existence
key = true;
} else {
key = false;
}
if (key = true) { // throw duplicate key exception
throw new DuplicateKeyException();
} else { // Put new uid into map
map.put(uid, new Student(name, major));
}
JOptionPane.showMessageDialog(null, "It worked...");
} catch (NullPointerException z) { // If the key doesn't exist
JOptionPane.showMessageDialog(null, "That record does not exist.");
} catch (DuplicateKeyException x) { // If the key does exist
JOptionPane.showMessageDialog(null, "That record already exists.");
} catch (NumberFormatException y) { // If user input is other than expected
JOptionPane.showMessageDialog(null, "You must enter integer.");
}
NullPointerException和NumberFormatException按预期工作,直到实现DuplicateKeyException。
“catch DuplicateKeyException()”显示“异常DuplicateKeyException已被捕获。”
我试图修改例外顺序,以防它们过于宽泛。这似乎没有帮助解决这个问题。
我还是新手,非常感谢任何意见。