如何在try catch块之外访问Variable

时间:2013-02-22 18:03:19

标签: java return try-catch return-value

我正在尝试从 try-catch block 的函数返回一个布尔值

但问题是我无法返回任何价值。

我知道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){}
}   
在我的项目中,这对我来说是一个非常严重的问题。 我用谷歌搜索,并尝试自己,但没有解决。

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

现在我严格要求

在我的jar文件中,我必须访问文本文件以查找值1或0,如果为“1”,则激活否则取消激活。

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

5 个答案:

答案 0 :(得分:9)

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

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

答案 1 :(得分:7)

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

答案 2 :(得分:3)

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

尝试以下方法:

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;
}  

答案 3 :(得分:0)

在try / catch块之前声明String字符串
然后在try / catch块之后编写if语句,如

    String strLine;

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

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

    return true;    

摆脱了其他区块。

答案 4 :(得分:0)

import java.io.*;
public class GameHelper 
{
    public String getUserInput(String prompt) {
        String inputLine = null;
        System.out.print(prompt + “ “);
        try {
            BufferedReader is = new BufferedReader(
            new InputStreamReader(System.in));
            inputLine = is.readLine();
            if (inputLine.length() == 0 ) return null;
        } 
        catch (IOException e) {
            System.out.println(“IOException: “ + e);
        }
        return inputLine;
    }
}

在编写程序之前,请确保先编写import java.io.*。现在,您甚至可以在trycatch

之外返回该函数。
相关问题