aspose file tools*
The moose likes Beginning Java and the fly likes Exception Handling Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Exception Handling" Watch "Exception Handling" New topic
Author

Exception Handling

Karine Roy
Greenhorn

Joined: Jul 11, 2011
Posts: 13
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

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.


[Jess in Action][AskingGoodQuestions]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
... 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

Joined: Oct 27, 2005
Posts: 19785
    
  20

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?


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
If you have managed to close System.in, there's nothing you can do about it ...
Karine Roy
Greenhorn

Joined: Jul 11, 2011
Posts: 13
Thanks guys, this helped a lot!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
You're welcome
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Exception Handling