• Post Reply Bookmark Topic Watch Topic
  • New Topic

Try-Catch Block Error "Variable might not have been initialized"  RSS feed

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I want to use a try catch block, but I am not sure how to fix this problem:


The purpose of the try-catch is to catch blank input.

The problem with this is that underneath the try - catch I get an error saying that the variable might not have been initialized. I know why this happens. I know I could initialize the varaible before the try - catch, but there is no default or null I can set an int as. If I initialized it as 0, the blank input will no longer be catched.

Any ideas on how to make this problem disappear?

Thanks!
Jordan
 
Sheriff
Posts: 22846
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Two steps.

First: decide what you would like the value of variable a to be if the input data fails the parsing test (the code path through the catch block). Zero sounds to me like a plausible choice but you might have reason to choose something else.

Second: either assign that value to a as part of the declaration, or assign it to a in the catch block.

If I initialized it as 0, the blank input will no longer be catched.


Did you try that? What you wrote there isn't correct -- and you can test it quite easily.
 
Greenhorn
Posts: 14
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Instead of using primitive datatype int, you can use Integer object. You can initialized the Integer object to null.
 
Jordan Ruetz
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh, I see what I was doing. I had something like this:


Which is obviously going to result in no error. So, in this example, if I do something with height, will it all have to be in the try block? Pretty sure so..., right?
 
Paul Clapham
Sheriff
Posts: 22846
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, that's right. Give it a try and you'll see.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!