Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

parsing question

 
Faheem Khan
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I have a quick question about 'parse exceptions' in...

1. Integer.parseInt(...)
2. DataFormat's parse() method.

I've noticed that Integer.parseInt() throws an unchecked run-time exception (NumberFormatException which extends IllegalArgumentException) when it can't parse an integer e.g.
int a = Integer.parseInt("4a");

But on the other hand... if we have

String someStringToParse = ...;
DateFormat df = DateFormat.getDateInstance();
try{
df.parse(someStringToParse);
}catch(ParseException p){
....
}

We're forced to handle (or declare) a ParseException.

Why didn't the Java designers have Integer.ParseInt(...) throw a ParseException or make the DateFormat parse method throw a DateFormatException(doesn't exist) or atleast make the NumberFormatException a checked exception for some kind of consistency in the different parsing methods?

Thanks for your time,

Faheem
 
Stephan van Hulst
Bartender
Pie
Posts: 5371
52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Likely because the methods were designed by different architects with different ideas.

In my opinion, the date parsing method should have thrown an unchecked exception as well.

Both classes should then provide methods that let you check whether a given string is valid for parsing. Sadly, this isn't the case.
 
Javin Paul
Ranch Hand
Posts: 295
Eclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree, unchecked Exception results in more cleaner code than checked exception so in this case DateFormat.parse() should throw unchecked Exception.
 
Faheem Khan
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the replies

I guess it's something to look out for on the exam.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic