2013-02-22 61 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块。