• Post Reply Bookmark Topic Watch Topic
  • New Topic

is possible accessing variable in try?  RSS feed

 
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear,
I have a variable which is filled in a try catch part. Can I have access to this variable out of try catch section? If yes, can you give me an idea about that?

my code is something like this:


the price variable filled in try but I wanna have access to that out of try catch.

thankyou,
Sahar.


[HENRY: added code tags]
 
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The price variable is declared to be in the block scope of the while loop. It is not accessable outside of the while loop.

If you want it accessable, you would need to declare it at a bigger scope -- say in the beginning of the method, so that it can be accessed at method scope.

Henry
 
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
something like this:

 
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To reiterate what the other respondents said: Variables can only be referenced from point of declaration to the end of the encompassing block. (For loops and parameters, the scope is the loop's block, or the body of the method.) This rule applies for the block associated with a "try", or any other block.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!