Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does the catch block give an error with variable not initialized in Java

Tags:

java

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?

like image 599
gizgok Avatar asked Jan 05 '12 10:01

gizgok


People also ask

What does it mean if a variable has not been initialized in Java?

Initializing a variable means specifying an initial value to assign to it (i.e., before it is used at all). Notice that a variable that is not initialized does not have a defined value, hence it cannot be used until it is assigned such a value.

What if there is an error in catch block?

Answer: When an exception is thrown in the catch block, then the program will stop the execution. In case the program has to continue, then there has to be a separate try-catch block to handle the exception raised in the catch block.


1 Answers

If there is an exception thrown in your try block, then the variable num may indeed not have been initialised. If you include the catch block, then execution can continue to the error line regardless, and thus the compiler reports the error you state.

If you remove the catch block, 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 the try.

(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 catch block...)

like image 55
David M Avatar answered Oct 16 '22 09:10

David M