我收到Java中的錯誤初始化變量:在try catch塊
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)
這裏是我的代碼:
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]);
}
}
}
考慮在'b1 = ...'之後的'try'內移動'for(...)'以僅在成功初始化時打印數組內容。現在,如果'b1'由於異常而未被賦值,那麼當進入'for()'時它不會被初始化, - 因此你會得到這個錯誤。 –
不要吞噬異常。這不僅是很好的一般建議,我認爲它也將解決您的具體問題。 –
@SashaSalauyou謝謝..它的工作..但你能告訴我爲什麼我的代碼有問題。這是由於嘗試範圍? – smasher