我花了几个小时试图找出我的 java 异常处理出了什么问题。我遵循所有书籍和网站创建海关异常(exception)、抛出它们并 try catch 它们。它们扩展了 RuntimeException (因为它们是在 ActionEvent 中抛出的),所以我认为不需要在方法头中声明 throws 子句。但 catch 子句不会运行。相关代码如下:
public void handle(ActionEvent event){
Object selectedButton = event.getSource();
if (selectedButton == b1)
{
String passwordStr1 = password1.getText();
String passwordStr2 = password2.getText();
{
if(passwordStr1.equals(passwordStr2))
{
if(PasswordCheckerUtility.isValidPassword(passwordStr1)== true)
{
Alert validAlert = new Alert(AlertType.INFORMATION);
validAlert.setTitle("Password Status");
validAlert.setHeaderText("Password is valid");
validAlert.showAndWait();
}
else
try
{
throw new UnmatchedException("The passwords do not match");
}
catch(UnmatchedException ue) {
Alert unEAlert = new Alert(AlertType.ERROR);
unEAlert.setTitle("Password Status");
unEAlert.setContentText(ue.getMessage());
}
}
}
和
public class UnmatchedException extends RuntimeException{
public UnmatchedException(String message)
{
super(message);
}
}
最佳答案
我尝试了一个更基本的示例,它似乎有效。也许问题出在代码的其他方面。这是我使用的:
主要方法:
public static void main(String...args){
handle(null);
}//main()
处理方法:
public static void handle(ActionEvent event){
try {
throw new UnmatchedException("The passwords do not match");
} catch(UnmatchedException ue) {
System.out.println(ue.getMessage());
}
}
以及单独类中的自定义异常:
public class UnmatchedException extends RuntimeException{
private static final long serialVersionUID = 1L;
public UnmatchedException(String message)
{
super(message);
}
}
关于java - 如何在 Java 中使用自定义异常?我已按照步骤操作,但我的 catch 条款无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52231578/