• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

simple Exception handling

 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
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

 
William Barnes
Ranch Hand
Posts: 986
Eclipse IDE Firefox Browser Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ...
Regards,
Manfred.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank You Manfred!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic