This is the code that I\'ve written.
int num;
try {
num=100;
DoSomething();
System.out.println(num);
} catch(Exception e) {
DoSomething1();
}
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...)