Hi all!
I have a question considering a simple try\ catch block.
suppose this is my code:
The code won't compile since the variable number may not be initialized. (it only gets value inside the try \ catch block, and therefore may not get a value at all.)
My question is, must i set number to an initialized value?
or is there another way to overcome it.
Thanks!
The problem is that fields have a default value, but local variables don't. When you declare a field, the JVM carves out enough memory space for it, and fills that space with 0s, so numbers are initialised to 0 (or 0.0), booleans to false and reference types to null. But there is no such mechanism for local variables, which are put onto a stack. To avoid the local variable simply copying whatever value was on the stack previously, the compiler insists that a local variable be initialised in every "path" through the code it is used in.
Parameters don't suffer this problem because every calling method must supply an argument with a value for every parameter.
You have "try . . . number = . . . " but if that line throws an Exception, then you might get the value for number after catch simply being whatever had been on the stack previously. That could be anything, even total nonsense. The prohibition against using un-initialised local variables is intended to avoid such errors.
Thanks all!
I understand what you say about initializing, and it makes a lot of sense.
however, 0 is an int value.
suppose i make my previous code, a method as:
suppose i initialize number to 0.
and suppose an exception occured, since someone typed a char 'x' for example.
in that case, my increase method will return 2, (0 +2) , which is an int value, but no number was actually inputted.
is there a way to not return anything? so i can be sure that a bad input was scanned?
In which case catching the exception is bad. You should use the check method instead:
Don't forget that call to input.next(). There is something (unless the stream is closed) but it's not an int; input.next() takes that something away. If you don't then the next call to hasNextInt() will return false again, and again, and again.