This is the code that I’ve written.
int num;
try {
num=100;
DoSomething();
System.out.println(num);
} catch(Exception e) {
DoSomething1();
} finally{
DoSomething2();
}
System.out.println(num); // Error Line
I get an error ‘The local variable num may not have been initialized’ on the error line that I’ve mentioned. On removing the catch block the error goes away. What is wrong here? Am I doing something incorrect?
If there is an exception thrown in your
tryblock, then the variablenummay indeed not have been initialised. If you include thecatchblock, then execution can continue to the error line regardless, and thus the compiler reports the error you state.If you remove the
catchblock, then execution will only reach the “error line” if there has been no exception, and in this case, the variable will have been initialised within thetry.(I’m assuming you already know about the need to intialise local variables before using them, and have focused on the behaviour you noticed with the
catchblock…)