[英]How to access a variable outside a try catch block
我正在尝试从具有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){}
}
我知道它有错误说缺少返回语句,但我希望程序完全像这样工作。
现在我对此很严格的原因
在我的 jar 文件中,我必须访问文本文件以查找值 1 或 0,如果“1”则激活,否则停用。
这就是我使用布尔值的原因。
只需在 try/catch 之外声明布尔值,并在 try 块中设置值
public boolean myMethod() {
boolean success = false;
try {
doSomethingThatMightThrowAnException();
success = true;
}
catch ( Exception e ) {
e.printStackTrace();
}
return success;
}
在您的方法中,如果抛出Exception
,则没有返回语句。 将return
语句放在异常处理程序中、 finally
块中或异常处理程序之后。
错误是在引发异常的情况下您没有返回任何内容。
尝试以下操作:
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;
}
在 try/catch 块之前声明 String strLine
然后在 try/catch 块之后写你的 if 语句,比如
String strLine;
try{
//......
}catch(Exception e){
//.....
}
if(strLine.equals("1"))
return false;
return true;
摆脱 else 块。
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.*
。 现在,即使在try
和catch
之外,您也可以返回该函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.