Reputation: 421
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?
Upvotes: 4
Views: 7393
Reputation: 393846
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 );
}
}
Upvotes: 8