Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 821
pkill Avatar asked Mar 14 '23 08:03

pkill


1 Answers

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

  }
}
like image 169
Eran Avatar answered Mar 22 '23 23:03

Eran