• Post Reply Bookmark Topic Watch Topic
  • New Topic

doubtscope of a variable declared in a try-catch  RSS feed

 
Vicky Chand
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in the code below i am getting an error that yeartest is not initialized even i try to use it in the if condition
Is the scope of a variable initialized in a try - catch within that block?

i tried initializing yeartest as public outside but then it did not get initialized (when i tried using it after the tr-catch block.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Vicky Chand:

Is the scope of a variable initialized in a try - catch within that block?


Let's make sure we have our terms straight. You declare a variable when you give its type and its name; i.e.,

int yeartest;

You initialize it when you assign a value for the first time, like

int yeartest = Integer.parseInt(year);

The scope of the declaration of any variable is the set of braces that surround the declaration. If you declare a variable inside a try block, then the scope is limited to that try block.

Now, the problem is that since the parseInt() call can throw an exception, it's possible that this initialization won't happen. Java will not let you access an uninitialized variable. Therefore you have two choices: you can either put allthe code that uses yeartest into the try block:



or declare and initialize the variable outside the try block, then assign it a new value inside the try block:



I generally prefer the first option when it's possible; putting related stretches of code together is better than breaking it up.
 
Vicky Chand
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried initializing and declaring it outside but when i tried changing its value in the try block but then again the value remained unchanged outside the try block.
I then tried declaring yeartest as a class variable instead of a local variable and then it worked
Thank You for your help
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Probably a bad idea to have a field which you are only using in one method; it ought to be a local variable.

Please show us how you manage to have a value unchanged.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!