As the title suggests I am trying to catch an empty String. I have a class (the class of the object I am trying to create) that throws an Exception when the String is null or empty (check with str.isEmpty). When I try to create the object with an empty String in another class it works as intended and throws an Exception. However, I want this class to Catch that Exception and notify the user. But it never seems to Catch the Exception, even if I try to write Catch(Exception exc). Now I know a null or empty String is not illegal. But my intention was that the object class was supposed to make it so. Instead it seems as if the catch block doesn't care at all. I am starting to think that I would have to create my own exception class of some sort... or is there something I am missing? Here are the relevant parts of the code:
The object class constructor:
public Valueables(String name){
//name.trim().length() == 0
if(name == null || name.isEmpty()){
try {
throw new Exception("Subclasses of Valueables cannot take in an empty String or null value for the \"name\" constructor");
} catch (Exception e) {
e.printStackTrace();
System.exit(2);
}
}
else
this.name = name;
}
The other class (the new Trinket object is a subclass of Valueables. The one with the constructor code above):
while(loopPassErrorControl == false){
//I don't think the try loop is relevant. But just to make sure...
//Otherwise just ignore it
try{
TrinketForm Tform = new TrinketForm();
answer = JOptionPane.showOptionDialog(ValueablesFrame.this, Tform, "Nytt smycke", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options , null);
if (answer != JOptionPane.OK_OPTION){
return;
}
valueablesList.add(new Trinket(Tform.getName(), Tform.getGemstones(), Tform.getMetalSelected()));
loopPassErrorControl = true;
}catch(NumberFormatException | NullPointerException exc) {
JOptionPane.showMessageDialog(ValueablesFrame.this, "Något gick fel");
}
}
//Test
for(Valueables obj : valueablesList){
System.out.println(valueablesList);
}
First throw a RuntimeException on Valuable:
public Valueables(String name){
//name.trim().length() == 0
if(name == null || name.isEmpty()){
throw new RuntimeException("Subclasses of Valueables cannot take in an empty String or null value for the \"name\" constructor");
}
else
this.name = name;
}
And do not catch the exception.
Second, on the other class catch a RuntimeException and show a mesage:
...}catch(RuntimeException exc) {
JOptionPane.showMessageDialog(exc.getMessage());
}
Hope helped you!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With