我想从 personAge 方法中抛出异常的地方获取字符串消息,以便它显示一个人的定义错误。 如何从 throw new Invalid..("the message"); 获取消息
标签?
这是我的 Controller 中的代码
@FXML
void btnRegister(ActionEvent event) {
String name = txtName.getText();
String email = txtEmail.getText();
String phonenr = txtPhonenr.getText();
int year = Integer.parseInt(txtYear.getText());
int month = Integer.parseInt(txtMonth.getText());
int day = Integer.parseInt(txtDay.getText());
boolean validateName = PersonValidator.checkName(name);
boolean validateEmail = PersonValidator.checkEmail(email);
boolean validatePhonenr = PersonValidator.checkPhonenr(phonenr);
try{
PersonAge.personAge(year);
}catch (InvalidAgeException msg){
lblResult.setText(msg);
}
}
这就是抛出异常的地方:
public class PersonAge {
public static int personAge(int year) throws InvalidAgeException {
Date date = new Date();
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Norway"));
cal.setTime(date);
int thisYear = cal.get(Calendar.YEAR);
int age = thisYear - year;
if(age <=0 || age > 120){
throw new InvalidAgeException("Age is invalid! Try again");
}
return age;
}
}
最佳答案
您只需要在异常上调用 getMessage() 即可:lblResult.setText(msg.getMessage());
关于java - 如何在 lblText.steText() 中设置预定义消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59868926/