java - 如何在 Java 中使用自定义异常?我已按照步骤操作,但我的 catch 条款无法正常工作

标签 java exception try-catch

我花了几个小时试图找出我的 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/

相关文章:

java - 从 MainActivity 调用时服务未启动

java - 使用 iText 在字符串下划线

java - Java 中的异步开源工作流软件

python - 为什么列表没有像字典一样的安全 "get"方法?

python - 如何捕获尚未完全导入的模块的异常?

java - 无法在 Android 中扩展选项菜单

c++ - C++代码中的异常安全

java - 是什么导致了 java.lang.ArrayIndexOutOfBoundsException 以及如何防止它?

java - "Rethrow"到下一个 catch 子句

java - 为什么 try-catch 不解决未经检查的泛型转换中的警告?