-4

I have a driven menu class using switch and beside that a class, that class throws an exception when a wrong input is entered how can I got back after the exception and ask the user to input data again.

java class diamond:

public class Diamond 
{

private int x;

    public Diamond(int x) throws IllegalArgumentException 
    {
        if ((x % 2) == 0) 
        {
           System.out.println("\nx must be odd.");
           throw new IllegalArgumentException("x must be odd.");

        }
      this.x = x;

    }
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Ann
  • 1

1 Answers1

0

Please see this question regarding exceptions in general as well as this Java Tutorial.

I assume you have some code that is accepting user input and then creating an instance of the Diamond class.

You would wrap the code creating the Diamond instance in a try-catch block.

So, something like this:

Diamond d = null;
try{
    d = new Diamond(userInput);
}catch(IllegalArgumentException e){
   //Handle the exception
}

However, since this exception is thrown due to an input problem rather than a programming problem I tend to lean toward the idea that you should use a checked exception here.

As a general rule per the Java Tutorial:

If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

D.B.
  • 4,523
  • 2
  • 19
  • 39