这个问题让我陷入了巨大的try-catch循环.我想要更小.那么如何在循环中访问赋值?
$javac TestInit2.java TestInit2.java:13: variable unknown might not have been initialized System.out.println(unknown); ^ 1 error
码
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); } }
解决方法
编译器阻止你做一些很可能是错误的事情,因为在你的try-catch块之后,你可能会假设变量被初始化了.但是,如果抛出异常,则不会初始化它.
在使用变量之前,您需要将变量赋值给它.但是,如果要在赋值失败时将其指定为null,则可以将其指定为null.
因此,如果您希望变量在赋值失败时为null,请尝试以下操作:
String unknown = null; try{ unknown="cannot see me,why?"; }catch(Exception e){ e.printStackTrace(); } System.out.println(unknown);
如果要在捕获异常时将变量设置为其他内容,请尝试以下操作:
String unknown; try{ unknown="cannot see me,why?"; }catch(Exception e){ e.printStackTrace(); unknown = "exception caught"; } System.out.println(unknown);
此外,如果在分配失败的情况下继续执行方法没有意义,则可能需要考虑从catch块返回,或者抛出另一个将由调用者捕获的异常.例如:
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);