Java: how to access jobs in try catch – loop?
This problem got me into a huge try catch loop I want smaller So how do I access assignments in a loop?
$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 prevents you from doing something that is probably wrong, because after your try catch block, you may assume that the variable is initialized However, if an exception is thrown, it is not initialized
Before using a variable, you need to assign a variable to it However, if you want to specify it as null when the assignment fails, you can specify it as null
Therefore, if you want the variable to be null when the assignment fails, try the following:
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 when you catch an exception, try the following:
String unkNown; try{ unkNown="cannot see me,why?"; }catch(Exception e){ e.printStackTrace(); unkNown = "exception caught"; } System.out.println(unkNown);
In addition, if there is no point in continuing to execute the method in the event of allocation failure, you may need to consider returning from the catch block or throwing another exception to 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);