Java – Try and catch not working JOptionPane(Java)

javajoptionpaneswingtry-catch

I have a JList and a string that is the JList's selection. If you click a JButton, It displays your JList selection. If you don't click a JList selection, It returns an error, So i used try catch, but it still returned an error.

here is my code, there are no errors in editor.:

@Override
public void actionPerformed(ActionEvent e) {
    String choice = chooser.getSelectedValue().toString();
    String companyname = name.getText();
    try{
        JOptionPane.showMessageDialog(frame,"<html> Welcome to your new Company!<br><br>Company type: " + choice + "" + "<br>" + "Company Name: "  + companyname  + "" +"</html>"  );   
    }catch (Exception e1){
        JOptionPane.showMessageDialog(frame, "Please fill in both inputs");
    }
}           

And also the try works fine if there's no error, but the catch just doesn't work. I also tried to catch NullPointerException and if ,else if choose = null, but it still didn't work. Not even the option pane pops up with null in its place.

Best Answer

Just where would expect an exception to occur?

try{
    String choice = chooser.getSelectedValue().toString();
    String companyname = name.getText();
    JOptionPane.showMessageDialog(frame,"<html> Welcome to your new Company!<br><br>Company type: " + choice + "" + "<br>" + "Company Name: "  + companyname  + "" +"</html>"  );   
}catch (Exception e1){
    JOptionPane.showMessageDialog(frame, "Please fill in both inputs");
}

MIGHT be a better solution, given the fact that JList#getSelectedValue will return null if nothing is selected...but then you would need to catch a NullPointerException or Throwable instead of Exception

Updated with example

Branching by exception is not a good way to design applications. Exceptions should be used to trap unexpected states. You would seem that you are expecting invalid results.

A better approach would be to actually inspect each of the values in turn and determine if they are valid.

    Object value = chooser.getSelectedValue();
    if (value != null && value instanceof String) {
        String choice = chooser.getSelectedValue().toString();
        String companyname = name.getText();
        if (companyname != null && companyname.trim().length() > 0) {
            JOptionPane.showMessageDialog(frame,"<html> Welcome to your new Company!<br><br>Company type: " + choice + "" + "<br>" + "Company Name: "  + companyname  + "" +"</html>"  );   
        } else {
            JOptionPane.showMessageDialog(frame, "The company name is invalid, please provide one");
        }
    } else {
        JOptionPane.showMessageDialog(frame, "Your company type choice is invalid, please select one");
    }