Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Try Blocks and "cannot resolve symbol"

 
Hosh Nasi
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am currently taking an input using the tokenizer to break it into array elements and then parse into the appropriate int variables.

Of course trying to parse a string of "B" into an Int isn't going to be fun.. In fact it throws "NumberFormatException" so I figured I would put it in a try block and recall my input method in this case.

However I get the Cannot Resolve Symbol Error. This is a quick snip

 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A set of curly braces defines a "scope". A variable name defined inside a scope can't be used outside that scope. So the variable nMsgType, defined inside the "try" block, can only be used inside the "try" block.

You can fix this in two ways. One would be to break the declaration into two lines:



Another way -- and in fact, the way I generally prefer to do this -- is to make your "try" block bigger, so that the "catch" is pushed to the end of the routine, and all the code that used nMsgType moves inside the try block.
 
Hosh Nasi
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another way -- and in fact, the way I generally prefer to do this -- is to make your "try" block bigger, so that the "catch" is pushed to the end of the routine, and all the code that used nMsgType moves inside the try block.


Is this the way it should be done? Do you loose any control in the end having the try block covering a larger area? I do see the advantages though.
 
Henrique Sousa
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Having the catch clause pushed down the code allows you to reduce variable scope, but sometimes you have to deal differently with exceptions, so it's all about what goes in the try clause. Speaking with code, it would be a choice between this:


and this:



When you nest a lot of try/catch blocks it may get somewhat confusing (been there, done that), so you ought to do whatever fits you best.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic