4

I've been investigating Java's ParseException, when trying to write my own method that parses from a String to an int, and have two questions:

  1. When should I throw it? Java's Integer.parseInt(String string) throws a NumberFormatException when an invalid input is given (makes sense with it being a subclass of IllegalArgumentException), and does not throw ParseException at all.
  2. What is "errorOffset"? ParseException's constructor forces you to give it a value - what does it mean?
resueman
  • 10,389
  • 10
  • 29
  • 43
  • For the second question, the `getErrorOffset` method tells you what it's for. It's "the position where the error was found." – resueman Dec 03 '15 at 21:25
  • What does that mean though? The position the error was found in the String? Or the method? Is a ParseException then caused by some error (eg a letter) in the String? – Ben Patterson Dec 03 '15 at 21:32
  • I interpret it as the position in the `String`. Telling a position in the method wouldn't be very useful information to most callers, since the details of the implementation shouldn't matter. – resueman Dec 03 '15 at 21:34
  • In the string. Parsing `"987A65"` would show error offset at index `3`. – Andreas Dec 03 '15 at 21:35
  • That's true, thanks. Does that answer the first question then? `ParseException` should be thrown when there is a problem in the String? Then is it preferable to throw `ParseException` or `NumberFormatException`? – Ben Patterson Dec 03 '15 at 21:38
  • NumberFormatException should be thrown. ParseException is usually when conversion between type format. You usually saw parseException when you try parse a date. – logger Dec 03 '15 at 21:46

1 Answers1

1

Throwing a ParseException for a parseXYZ() method (that actually parses something) is perfectly valid. Integer.parseInt throws a NumberFormatException since it is a subtype of RuntimeException and therefore does not force you to surround it with try-catch (This is not true for ParseException).

The offset field is used to identify the position for which the error occurred. With that information, you may be able to use whatever partial data you already parsed.