如何在try catch块之外访问Variable

Rum*_*han 3 java return try-catch return-value

我试图从我的具有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){}
}   
Run Code Online (Sandbox Code Playgroud)

在我的项目中,这对我来说是一个非常严重的问题.我用谷歌搜索,并尝试自己,但没有解决.

我希望现在我会找到一些解决方案.我知道它有错误说返回语句丢失 但我希望程序完全像这样工作.

现在我对此严格原因

在我的jar文件中,我必须访问文本文件以查找值1或0,如果为"1",则激活其他取消激活.

这就是我使用布尔值的原因.

Luc*_*cas 10

只需在try/catch之外声明布尔值,并在try块中设置值

public boolean myMethod() {
    boolean success = false;
    try {
        doSomethingThatMightThrowAnException();
        success = true;
    }
    catch ( Exception e ) {
        e.printStackTrace();
    }
    return success;
}
Run Code Online (Sandbox Code Playgroud)


rge*_*man 7

在您的方法中,如果Exception抛出a,则没有return语句.将return语句放在异常处理程序,finally块中或异常处理程序之后.


Col*_*n D 4

错误是在抛出异常的情况下您不会返回任何内容。

尝试以下操作:

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;
}  
Run Code Online (Sandbox Code Playgroud)