javaerror-handlingvariable-assignment

Java: how to access assignments in try-catch -loop?


The problem drives me to the big try-catch loops. I want smaller. So how to access assignments in the loops?

$ javac TestInit2.java 
TestInit2.java:13: variable unknown might not have been initialized
  System.out.println(unknown);
                     ^
1 error

Code

import java.util.*;
import java.io.*;

public class TestInit2 {

 public static void main(String[] args){
  String unknown;
  try{
   unknown="cannot see me, why?";
  }catch(Exception e){
   e.printStackTrace();
  }
  System.out.println(unknown);
 }
}

Solution

  • The compiler is stopping you from doing something that is most likely a mistake, since after your try-catch block, you would probably assume that the variable is initialized. If an exception is thrown, however, it will not be initialized.

    You will need to assign the variable to something before using it. It is, however, possible to just assign it to null, if you want it to be null if the assignment fails.

    So, if you want the variable to be null if the assignment fails, try this:

        String unknown = null;
        try{
            unknown="cannot see me, why?";
        }catch(Exception e){
            e.printStackTrace();
        }
        System.out.println(unknown);
    

    If you want to set the variable to something else if an exception is caught, try this:

        String unknown;
        try{
            unknown="cannot see me, why?";
        }catch(Exception e){
            e.printStackTrace();
            unknown = "exception caught";
        }
        System.out.println(unknown);        
    

    Also, if it doesn't make sense to proceed with the execution of your method if the assignment fails, you might want to consider either returning from the catch block, or throwing another exception which would be caught by the caller. For example:

        String unknown;
        try{
            unknown="cannot see me, why?";
        }catch(Exception e){
            e.printStackTrace();
            //return; // if you just want to give up with this method, but not bother breaking the flow of the caller
            throw new Exception("Uh-oh...", e); // if you want to be sure the caller knows something went wrong
        }
        System.out.println(unknown);