Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw an exception if parsing with Long.parseLong() fails?

I am trying to write some kind of a stack calculator.

Here is a part of my code where I am handling a push command. I want to push integers only, so I have to get rid of any invalid strings like foobar (which cannot be parsed into integer) or 999999999999 (which exceeds the integer range).

strings in my code is a table of strings containing commands like POP or PUSH, numbers, and random clutter already split by white characters.

Main problem:

I've got difficulties with throwing an exception for long parseNumber = Long.parseLong(strings[i]); - I don't know how to handle the case, when strings[i] cannot be parsed into a long and subsequently into an integer.

while (i < strings.length) {
  try {
    if (strings[i].equals("PUSH")) {
      // PUSH 
      i++;
      if (strings[i].length() > 10)
        throw new OverflowException(strings[i]);
      // How to throw an exception when it is not possible to parse 
      // the string?
      long parseNumber = Long.parseLong(strings[i]); 
      
      if (parseNumber > Integer.MAX_VALUE)
        throw new OverflowException(strings[i]);
      
      if (parseNumber < Integer.MIN_VALUE)
        throw new UnderflowException(strings[i]);
      number = (int)parseNumber;
      stack.push(number);      
    }
    // Some options like POP, ADD, etc. are omitted here
    // because they are of little importance.
  }
  catch (InvalidInputException e)
    System.out.println(e.getMessage());
  catch (OverflowException e)
    System.out.println(e.getMessage());
  catch (UnderflowException e)
    System.out.println(e.getMessage());
  finally {
    i++;
    continue;
  }
}
like image 265
Mateusz Piotrowski Avatar asked Dec 14 '22 14:12

Mateusz Piotrowski


1 Answers

Long.parseLong(String str) throws a NumberFormatException if the string cannot be parsed by any reason. You can catch the same by adding a catch block for your try, as below:

catch ( NumberFormatException e) {
    System.out.println(e.getMessage());
}
like image 85
Iqbal S Avatar answered May 12 '23 21:05

Iqbal S