Java how to access a variable outside the try-catch block

﹥>﹥吖頭↗ 提交于 2019-12-10 19:08:23

问题


I am a beginner in java, and was playing around with try-catch block.However, I am not able to get the variable outside the try-catch block.

The following code works.

class factorial{
public static void main(String[] args){
    try {
         int num = Integer.parseInt(args[0]);
         System.out.println(num );
    }
    catch(Exception e){
        System.out.println(e+" Cannot convert arg to int, exiting..");
    }


}
}

But the following doesn't works.

class factorial{
public static void main(String[] args){
    try {
         int num = Integer.parseInt(args[0]);
    }
    catch(Exception e){
        System.out.println(e+" Cannot convert arg to int, exiting..");
    }
     System.out.println(num );
}
}

Tried the following as well

class factorial{
public static void main(String[] args){
    int num;
    try {
         num = Integer.parseInt(args[0]);
    }
    catch(Exception e){
        System.out.println(e+" Cannot convert arg to int, exiting..");
    }
     System.out.println(num );

}
}

But the error says The local variable num may not have been initialized

How can I get rid of this error?


回答1:


You should declare the variable before the try block (in order for it to still be in scope after the try-catch blocks), but give it an initial value :

class factorial{
  public static void main(String[] args){
    int num = 0;
    try {
         num = Integer.parseInt(args[0]);
    }
    catch(Exception e){
        System.out.println(e+" Cannot convert arg to int, exiting..");
    }
    System.out.println(num );

  }
}


来源:https://stackoverflow.com/questions/33334327/java-how-to-access-a-variable-outside-the-try-catch-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!