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?
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.
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.
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...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With