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?
MIGHT be a better solution, given the fact that
JList#getSelectedValue
will returnnull
if nothing is selected...but then you would need to catch aNullPointerException
orThrowable
instead ofException
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.