-1

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?

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
Seo-Jun Koh
  • 13
  • 1
  • 7
  • 1
    You don't call `setId()` anywhere in your loop. No exceptions are thrown. – Jim Garrison May 17 '16 at 23:18
  • Does your code in the try block throws exception. Unless it throws it won't execute the catch block – Dan Hunex May 17 '16 at 23:19
  • You are not calling `setId()` anywhere, but you are actually testing every `id` from `nextLine`, so you never detect any invalid id that would throw the exception. –  May 17 '16 at 23:19

1 Answers1

1

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.

nclark
  • 1,022
  • 1
  • 11
  • 16