• Post Reply Bookmark Topic Watch Topic
  • New Topic

try catch local variable may not be initialized?  RSS feed

 
Saad Zahoor
Ranch Hand
Posts: 82
Android
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Error : the local variable z may not be initialized ?? in last line of code

I just declare z as variable in first line then why it it is saying z is  not initialized !

 
Liutauras Vilda
Sheriff
Posts: 4917
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Saad Zahoor wrote:why it it is saying z is  not initialized !
It doesn't say that. It says:
Saad Zahoor wrote:may not be initialized
As you understood, it is totally different. Question is why and in which cirmustances it can happen?

Please tell us, what do you know about the 'try' and 'catch' blocks?
 
Saad Zahoor
Ranch Hand
Posts: 82
Android
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if thing is not accurate or does not exists it throw exception and we can handle it . In case of Files if the specified file does not exists then it throw exception !
 
Liutauras Vilda
Sheriff
Posts: 4917
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alright, so, if things, as you say not accurate, things go wrong, and what's inside try block may not go well as it supposed to, so in this exact scenario 'z' may not be initialized.
Not knowing what you're trying to build here, can advice only just to use finally block to initialize 'z' to some sort of default value. OR initialize right at the beginning.

But in general we don't have material to work on and discuss better ways to accomplish one or another task.
 
Fred Kleinschmidt
Bartender
Posts: 571
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It does not make sense to have a try-block that does not include something that might throw an exception.
Now, if you were to add some statement in that block before the "z=x/3; statement), and that addition could throw an exception, then it is easier to visualize why the compiler is giving you that warning message.

If the new statement were to throw an exception, then control would transfer immediately to the catch-block without executing the assignment of x/3 to z. Then control continues to the print statement that references z, but z has not been assigned any value - hence the warning.
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Fred Kleinschmidt wrote:. . . hence the warning.
Good explanation, but that isn't a warning. It is a full‑blown error and the javac tool finds it impossible to allow such code to be executed at all. That is why there is a compile‑time error.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!