开发者

creating our own exceptions class in java

开发者 https://www.devze.com 2023-03-12 21:41 出处:网络
I want to create my own exception class and catch the null value returned when the user presses the inputDialog boxes cancel button. Basically If the user presses cancel I dont want the program to cra

I want to create my own exception class and catch the null value returned when the user presses the inputDialog boxes cancel button. 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.

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;
    }

//whe开发者_C百科re inputDialog is called

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.

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. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消