I'm trying to make a program that reads in numbers and commands and prints the list of numbers.
I am trying to solve one problem at a time and this is about exception handling. I am still not familiar with the whole exception handling that is why I get confused.

reads in 1 2 3 + p abc
the + sign means adding 3 and 2
the p means printing the numbers
and abc is the one I want to catch

I did an IMM exception, however, I just want to know if there is another way to doing this. Or is creating my own exception going to be better?

 public static void main(String[] args) {
      int num;

      Scanner input = new Scanner(System.in);

      MyStack stack = new MyStack();

                  num = input.nextInt();
              else if (input.next() == "+"){

          catch (InputMismatchException ex)
              System.out.println("too long: ");

You will need to test for incorrect input and throw an Exception if it's incorrect. If one of the existing Exceptions in the Java API correctly describes your situation (maybe DataFormatException ?) then use that. If not, define your own Exception. There's no right or wrong here, just do whatever is clearest for someone reading the code.

the first thing you need in order to catch an exception, is that an exception must be thrown. In your case, it doesn't matter wetter you catch InputMisMatchException, or one you defined yourself, simply because it won't be thrown.

to clarify: you are reading instances of String. maybe you can (according to your analysis) see why "abc" is an invalid value, but for the compiler, "abc" is a valid String, and there is no need to throw an Exception while reading it.

what you can do, is, after your

else if (input.next() == "+"){

which, by the way, is wrong and might lead to invalid results (in order to compare Strings for value, not reference, never use the '==' operator, always use the equals method)

so, step one, replace the above by:

else if (input.next().equals("+")){

but, back to my original point: after this, add:

  // when reaching this, something went wrong, as in 
  // an invalid value has been read
  throw new InputMisMatchException("Invalid value entered.");

if you later on have to add subtract, multiply, division, ... or others, make sure you implement those before this else block.

and ... that's basically all there is to it.

Before you can go further in exception, you need to check if the class methods you are using will throw any exception. If they throw, what are those exceptions, so that you can try to catch them.


hasNextInt() returns a boolean and will throw IllegalStateException if an only if the scanner is closed. What you are doing has nothing to do with the exception.
hasNext() returns a boolean and will throw IllegalStateException (again).
next() returns a String and could throw IllegalStateException if the scanner is closed or NoSuchElementException if no token available.

When you use "try" block, you must "catch" the correct exception. If you do not catch the correct exception being thrown within the try block, your program will ignore the exception. You could use a universal exception handling (i.e. catch (Exception e) { ... }), but that likely means you have no idea what your program is doing.

That said, your current program will never catch anything. Also, you would need to reformulate your problem first. What is the expected format of input? How would you accept the input? What order would you be expecting for the input? Think of it as states. What type of input do you expect next?

For example, first state is when input is only number all the way. Once the input is changed to a mathematical operator, then it goes to the next state. If the input is not what you expected, throw an exception. Then after a mathematical operator, what should be next? Could be be a number again? If so, let goes back to the first state. Then what should always come after a mathematical operator? Let's say a letter p. If anything goes after this, then it is wrong.

        not a number or math op
  | math op      p     .-.   extra     v
  A ------> B ------> | C | ------> EXCEPTION
 /^^       ' '         ._.            ^
/  \\     /   \                      /
'--' '---'     '--------------------'
number number        not letter p

A - input is a number,
    goes back to A if input is a number,
    goes to B if a math op is entered,
    goes to EXCEPTION if not
B - goes to C if enter p,
    goes to A if enter a number,
    goes to EXCEPTION if not
C - done if no more input,
    goes to EXCEPTION if there is an input

Edited 2 Years Ago by Taywin

This article has been dead for over six months. Start a new discussion instead.