Skip to content
Advertisement

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

    }
}

Advertisement

Answer

The problem here is that getBytes(String encoding) throws UnsupportedEncodingException. If such an exception occurs in your code (this will happen if you put wrong encoding for example getBytes("foo")), your byte array will remain uninitialized. The catch block will handle the exception and continue with the for loop where you are trying to use b1. The compiler sees that possibility and throws an error in order to prevent usage of uninitialized variable later.

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");
         for(int i =0;i<s2.length();i++)
         {
            System.out.println(b1[i]);
         }
        }
        catch(UnsupportedEncodingException uee){ 
            //handle the exception or at least log it
        }
    }
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement