'Initializing variable in try catch block
I am getting the error in Java:
Exception in thread "main" java.lang.Error: Unresolved compilation problem
The local variable b1 may not have been initialized at Test.main(Test.java:20)
Here is my code:
import java.lang.String;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
char a[]={'s','k'};
String s0=new String(a);
String s1=new String("Amar");
String s2= "amarnath";
byte[] b1;
try{
b1=s2.getBytes("ASCII");
}
catch(Exception e){}
for(int i =0;i<s2.length();i++)
{
System.out.println(b1[i]);
}
}
}
Solution 1:[1]
PROBLEM
If there is an error inside the try block, then b1 would not have been initialized and would have a value of null.
If this happens, then there would be a problem when you try and print out b1's values in the following line:
System.out.println(b1[i]);
Java is cautious and won't let the possibility of that happen.
SOLUTIONS
- Initialize
b1with a default value- This will prevent the possibility that
b1is uninitialized (which is what Java worried about)
- This will prevent the possibility that
- Put the
forloop inside thetryblock (as @SashaSalauyou said in the comments)- If there is an error with
b1's inialization in thetryblock, then the block will quit, and theforloop would not be run. Therefore, there would be no code using the uninitialized variable such as in aforementioned line of code.
- If there is an error with
Solution 2:[2]
The compiler complains because if the b1 is not initialized and if something bad happens inside the try block, it will be then used in the following block, System.out.println(b1[i]);, uninitialized.
In order to make it compile, you should initialize your variable at least with null, as it is local variable.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Ioan |
