Seo-Jun Koh Seo-Jun Koh - 6 months ago 17
Java Question

Try / Catch not displaying Exception error message

Hey there so in my class I had written this:

public void setId(String id) { ...
if (id.matches("[a-zA-Z]{3}-\\d{4}")) {
this.id = id;
} else { // id is invalid: exception occurs
throw new IllegalArgumentException("Inventory ID must be in the "
+ "form of ABC-1234");
}

}


then in my main program I did this:

while (idLoopTrigger == true) {
try {

System.out.println("Please enter id: ");
id = in.nextLine();

if (id.matches("[a-zA-Z]{3}-\\d{4}")) {
idLoopTrigger = false;
}

} catch (Exception ex) {

//print this error message out
System.out.println(ex.getMessage());

}

}


So it will loop until the user inputs the correct info but it won't display the exception message from my class. Thoughts?

Answer

It looks like you're approximating the content of the setId() method in main() instead of calling it.

I'm not sure where this setId() method is supposed to live, but assuming it's defined in the same class as your main():

while (idLoopTrigger == true) {

    try {
        System.out.println("Please enter id: ");
        id = in.nextLine();
        setId(id);
        idLoopTrigger = false;

    } catch (Exception ex) {

        //print this error message out
        System.out.println(ex.getMessage());
    }

}

This seems to be at least close to what you're looking for.