The following code is part of a larger application:
public static void METHOD_NAME(Object setName, int setLength){
tryLoop:
for( ; ; ){
try{
setName = new Stack(setLength);
break tryLoop;
}catch (InstantiationException e){
System.err.println(e.getMessage());
SET_NUM(1);
continue tryLoop;
}
}
}
Whenever I try to use the stack object that was initialized within the try block, it cannot be found unless the reference to it is within the try block. Why is this and how can I avoid it in the future?
I suspect you're under the impression that this:
setName = new Stack(setLength);
will have some impact on the argument passed in by the caller. It won't. Java is strictly pass-by-value, whether that value is a primitive type value or a reference.
In other words, if you do this:
Object foo = null;
METHOD_NAME(foo, 5);
then foo
will still be null
afterwards.
I suggest you return the value from your method instead. For example:
public static Stack METHOD_NAME(Object setName, int setLength){
while(true) {
try {
return new Stack(setLength);
} catch (InstantiationException e){
System.err.println(e.getMessage());
SET_NUM(1);
}
}
}
Note the return instead of breaking to a label, and while(true)
which I find more readable than for (; ;)
.