2013-02-22 123 views
3

我試圖從具有try-catch塊如何在try catch塊

我的功能返回一個布爾值但問題是我不能返回任何值之外訪問變量。

我知道try-catch塊內部的變量不能在外部訪問,但仍然是我想要的。

public boolean checkStatus(){ 
     try{ 


     InputStream fstream = MyRegDb.class.getClassLoader().getResourceAsStream("textfile.txt"); 
     // Use DataInputStream to read binary NOT text. 
     BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); 
     String strLine; 

     //Read File Line By Line 
     strLine = br.readLine(); 
     // Print the content on the console 
     System.out.println (strLine); 

     ind.close(); 
     if(strLine.equals("1")){ 

      return false; 
     }else{ 
      return true;  
     } 

    }catch(Exception e){} 
} 

在我的項目中,這對我來說是一個超級嚴重的問題。 我用Google搜索了一下,並嘗試過自己,但沒有解決。

我希望現在我會找到一些解決方案。 我知道它有錯誤,說返回語句丟失但我想程序正是這樣工作。

現在原因,我嚴格到這種

在我的jar文件我要訪問的文本文件查找值1或0,如果「1」,則激活其他禁用。

這就是爲什麼我使用布爾值。

回答

2

錯誤是你在拋出異常的情況下沒有返回任何東西。

嘗試以下操作:

public boolean checkStatus(){ 
    boolean result = true; // default value. 
    try{ 

     InputStream fstream = MyRegDb.class.getClassLoader().getResourceAsStream("textfile.txt"); 
     // Use DataInputStream to read binary NOT text. 
     BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); 
     String strLine; 

     //Read File Line By Line 
     strLine = br.readLine(); 
     // Print the content on the console 
     System.out.println (strLine); 

     ind.close(); 
     if(strLine.equals("1")){ 

      result = false; 
     }else{ 
      result = true;  
     } 

    }catch(Exception e){} 
    return result; 
} 
8

剛剛宣佈的try/catch的布爾外,並在try塊

public boolean myMethod() { 
    boolean success = false; 
    try { 
     doSomethingThatMightThrowAnException(); 
     success = true; 
    } 
    catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return success; 
} 
7

在你的方法設置的值,如果Exception被拋出,那麼就沒有return語句。將return語句放在異常處理程序中,在finally塊中,或在異常處理程序之後。

0

聲明字符串strLine中brfore的try/catch塊
,然後寫你如果喜歡

String strLine; 

    try{ 
     //...... 
    }catch(Exception e){ 
     //..... 
    } 

    if(strLine.equals("1")) 
     return false; 

    return true;  

的try/catch塊後聲明擺脫else塊。