Java 调用ioexception抛出函数

Java 调用ioexception抛出函数,java,android,exception-handling,Java,Android,Exception Handling,我无法调用此函数,尽管它确实抛出amnd handle IOException public static String[] readtxt(String f) throws IOException{ try{ FileReader fileReader=new FileReader(f); BufferedReader bufferedReader=new BufferedReader(fileReader); List<String> li

我无法调用此函数,尽管它确实抛出amnd handle IOException

 public static String[] readtxt(String f) throws IOException{
    try{
     FileReader fileReader=new FileReader(f);
     BufferedReader bufferedReader=new BufferedReader(fileReader);
     List<String> lines=new ArrayList<String>();
     String line=null;
     while((line=bufferedReader.readLine())!=null)lines.add(line);
     bufferedReader.close();
     return lines.toArray(new String[lines.size()]);
    }catch(IOException e){return null;}     
}

 ...    
 private String[] truth=MainActivity.readtxt(file); 
 // ^ wont compile: Unhandled exception type IOException
publicstaticstring[]readtxt(stringf)抛出IOException{
试一试{
FileReader FileReader=新的FileReader(f);
BufferedReader BufferedReader=新的BufferedReader(文件阅读器);
列表行=新的ArrayList();
字符串行=null;
而((line=bufferedReader.readLine())!=null)行。添加(line);
bufferedReader.close();
返回lines.toArray(新字符串[lines.size()]);
}catch(ioe异常){returnnull;}
}
...    
私有字符串[]truth=MainActivity.readtxt(文件);
//^无法编译:未处理的异常类型IOException

您需要像下面这样处理异常

 try{ 
      private String[] truth=MainActivity.readtxt(file); 
 }catch(IOException exception){
      exception.printStackTrace()
 }

您或者需要像这样处理方法引发的异常

try{ 
    private String[] truth = MainActivity.readtxt(file);
}catch(IOException ioe){
    // Handle Exception
}
public static String[] readtxt(String f) {
或者您可以从方法定义中删除
throws
子句,如下所示

try{ 
    private String[] truth = MainActivity.readtxt(file);
}catch(IOException ioe){
    // Handle Exception
}
public static String[] readtxt(String f) {
看看你的代码,我真的怀疑这个方法是否真的会抛出任何
IOException
,因为你已经抓到了。因此,您可以删除该子句

但是如果您真的想抛出它,那么您可以在方法中删除try-catch,或者在catch块中执行类似的操作

catch(IOException ioe){
    // Throw IOE again
    throw new IOException(ioe);
}

您将方法定义为抛出IOException

public static String[] readtxt(String f) throws IOException
这意味着调用此方法的任何方法都必须处理此类异常(在catch块中),您没有在调用此方法的方法中处理这些异常,因此会引发此错误

但是,您已经处理了可能抛出的任何IOException。声称该方法可能抛出IOException是不必要的(或正确的),因为它永远不会抛出IOException。只需删除
即可引发IOException


您已通过返回null来处理异常,这可能正确,也可能不正确,具体取决于您的实现。在IOException上,将返回null,程序将继续运行,就好像什么也没发生一样。您也可以选择给出错误消息,但正如我所说的,这取决于您的具体情况

创建一个函数,该函数不会引发异常或在readtxt调用周围添加try/catch块。另外,我不明白为什么要抛出它,只需删除“throws IOException”。我认为返回null不是问题,throws IOException是