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

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

    Local variables in Java are not initialized automatically. So you need to initialize it before use them.

    int num=0;
    try
    {
      .. 
    }
    ...
    

    Fore more info read - Definite Assignment (JLS - 16.2.15 try Statements)

提交回复
热议问题