I’m trying to get a handle on Java’s error handing. Is it possible to have small try/catch blocks that do one thing and then return the result of it’s operation back to the main scope?
It seems like everything has to go inside of the try block, which seems a little odd.
I’ve set up the following test:
public class test {
public static void main(String[] args) {
System.out.println(0-10);
int guess;
try {
guess = 5;
}
catch(Exception ex) {
System.out.println("bugger");
}
System.out.println(guess);
}
}
Just for sake of example, I declare a variable, and then assign it a value inside of the try block, but it seems to only exist inside of the try block. Trying to print it outside of the try results in an error. Is there a way to pass information out of the try?
It results in an error because the compiler cannot know whether
guesswill have been initialized when it tries to print it at the end of the program. What if an exception is thrown inside yourtryblock andguessnever gets assigned to anything? You must first assign it to some default value at the start, e.g.int guess = 0.