Why doesn't the compiler understand that the variable is initialized in either the try
or the catch
block
and complains at the finally
block?
int i;
try {
i = 0;
}
catch (Exception e) {
i = 2;
}
finally {
System.out(i);
}
Why doesn't the compiler understand that the variable is initialized in either the try
or the catch
block
and complains at the finally
block?
int i;
try {
i = 0;
}
catch (Exception e) {
i = 2;
}
finally {
System.out(i);
}
If the initialization statement (i = 0;
) fails, then the program will continue with the finally
block, where the variable will still be un-initialized and this is why you get a compile-time error.
The compiler won't be able to know if i
will get initialized or not. It might fail for whatever reason and therefor the finally
block might not work.
If you print variable 'i' in catch block before initialization, it gives error because compiler thinks that an exception might be thrown before 'i' has been set in try block in which case 'i' would not have been initialized so is the case with finally here i.e. when you print 'i' in finally block compiler thinks that an exception might be thrown before 'i' has been set in catch block in which case 'i' would not have been initialized
Compiler doesn't understand that the variable is initialized in either the try or the catch block. Compiler complains because local variables should be declared and initialized at the same time but you have just declared it. If you use it in either block (try, catch, finally) without initialization compiler complain about it. Try it:
int i;
try {
System.out.println(i);
//i = 0;
}
catch (Exception e) {
System.out.println(i);
//i = 2;
}
finally {
System.out.println(i);
}