简体   繁体   English

在 java 中创建我们自己的异常 class

[英]creating our own exceptions class in java

I want to create my own exception class and catch the null value returned when the user presses the inputDialog boxes cancel button.我想创建自己的异常 class 并捕获用户按下输入对话框取消按钮时返回的 null 值。 Basically If the user presses cancel I dont want the program to crash.基本上,如果用户按下取消,我不希望程序崩溃。 how do i do that.我怎么做。 and I wanted to create my own exception class because I intend to put other custom exceptions in it for future use.我想创建自己的异常 class 因为我打算将其他自定义异常放入其中以备将来使用。

static private String showInputDialog()//utility function for userInput----------------
    {
        String inputValue = JOptionPane.showInputDialog("Please input something");

        if(inputValue.isEmpty() || !inputValue.matches("[A-Za-z]*"))
        {
            inputValue = showInputDialog();
        }

        return inputValue;
    }

//where inputDialog is called //调用inputDialog的地方

public void actionPerformed(ActionEvent evt)
{  
       String firstName = showInputDialog();
       String lastName = showInputDialog();
}

The exception is the result of a null value of inputValue, you can prevent getting the exception by checking for null yourself.异常是 inputValue 的null值的结果,您可以通过自己检查 null 来防止出现异常。

Also, your method now goes into recursion on every next iteration.此外,您的方法现在在每次下一次迭代时都会进行递归。 What you want to achieve functionally is "while nothing is input ask for input".您想要在功能上实现的是“在没有输入的情况下要求输入”。 This would translate into:这将转化为:

//utility function for userInput----------------
static private String showInputDialog()
{
    String inputValue = null;

    do {
        inputValue = JOptionPane.showInputDialog("Please input something");
    }
    while (inputValue != null && (inputValue.isEmpty() || !inputValue.matches("[A-Za-z]*")));

    return inputValue;
}

All you have to do is create a new class and extend Exception, but it is preferable to do checks for the value instead, since exceptions are slow and annoying to debug.您所要做的就是创建一个新的 class 并扩展 Exception,但最好检查该值,因为异常很慢且调试起来很烦人。 If you need something to happen only when the user hits cancel(and you thus get a null value), you could check for the null value outside of the method, and handle it as preferred for each method call.如果您仅在用户点击取消时才需要发生某些事情(因此您获得 null 值),您可以检查方法之外的 null 值,并将其作为每个方法调用的首选处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM