File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes simple 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 "simple Exception handling" Watch "simple Exception handling" New topic

simple Exception handling

Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
This is my first study into Exception handling. Why doesn't this code work? I've commented the part that I'd hoped would behave differently. Is it not possible to perform logical tests within the catch block?
Thank You

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
William Barnes
Ranch Hand

Joined: Mar 16, 2001
Posts: 986

Without trying to run the code I can say that you need to get into the catch block first. And the only way of getting into the catch block to throw the corresponding exception.
So in your case if you are not throwing "NumberFormatException" than you will never get into the catch block of code.

Please ignore post, I have no idea what I am talking about.
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
Hi Dirk,
Your error has nothing to do with Exception handling. You must have come from a C/C++ background to have made this error. Don't worry because it is probably the error that most beginning java programmers make.
When dealing with Strings in java the == operator doesn't work like you expect it to. The == operator just compares memory locations. In your case, the memory locations are different therefore you always go through your else case.
If you want to actually compare String contents then you must use the equals method. For example:
inputTextField.getText() == "one"
will always be false. But
inputTextField.getText().equals( "one" )
might be true or false depending on the inputTextField value.
It is the small things that cause the most problems and are the hardest to debug without stepping back and looking at the big picture. Another set of eyes is a great thing to have ...
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
Thank You Manfred!
I agree. Here's the link:
subject: simple Exception handling
jQuery in Action, 3rd edition