Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable not initialized in try catch block `finally`

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);
}
like image 264
forcewill Avatar asked Jan 09 '23 14:01

forcewill


1 Answers

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.

like image 130
Konstantin Yovkov Avatar answered Jan 17 '23 21:01

Konstantin Yovkov