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

后端 未结 7 1134
臣服心动
臣服心动 2021-01-12 00:42

This is the code that I\'ve written.

int num;
try {
    num=100;
    DoSomething();
    System.out.println(num);
} catch(Exception e) {
    DoSomething1();
}         


        
7条回答
  •  既然无缘
    2021-01-12 01:06

    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...)

提交回复
热议问题