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

后端 未结 7 979
臣服心动
臣服心动 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:00

    Exception handling can confuse the compiler. In this case, you know that an exception cannot possibly be thrown BEFORE the variable num is set, but the compiler doesn't know this.

    The compiler thinks that an exception might be thrown before num has been set in which case num would not have been initialized when you try to print it outside the try-catch block.

提交回复
热议问题