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?
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 );
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With