File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception Handling

 
Karine Roy
Greenhorn
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to catch an exception when the part number entered is not an integer. For some reason my "try - catch" is not working. Any advice?

 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The class "TextIO" you're using isn't part of the standard Java API; maybe an instructor gave it to you, or you got it from a book. You're assuming that the "getInt()" method is going to throw a NumberFormatException. That's a reasonable assumption, but perhaps it doesn't. For example, here is the first Google hit for a class by this name, and it, sadly, prints an error message instead of throwing an exception, and returns zero! This is a horrifyingly bad design; please, please don't learn from this as an example!

Try just using the java.util.Scanner class directly -- it'll behave the way you want, plus you'll be writing real code.
 
Campbell Ritchie
Sheriff
Pie
Posts: 47270
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
... and there is a way to stop Scanner throwing such exceptions. I am liable to get this wrong and Rob Spoor corrects my mistake, so let's try to get it right
 
Rob Spoor
Sheriff
Pie
Posts: 20381
46
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Looks good to me. The inScan.next() is very important; this consumes the non-int value. Without that line the code would loop forever because the non-int would cause hasNextInt to always return false.

I think that technically it's possible that inScan.next() can throw an exception if System.in is closed, but then again, who does that?
 
Campbell Ritchie
Sheriff
Pie
Posts: 47270
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you have managed to close System.in, there's nothing you can do about it ...
 
Karine Roy
Greenhorn
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys, this helped a lot!
 
Campbell Ritchie
Sheriff
Pie
Posts: 47270
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic