![](/img/trans.png)
[英]unreported IOException even though in try-catch block and throws Exception
[英]Unreported IOException error, but has “throws Exception” and Try and Catch is within method
我创建了一个Util类,该类返回一个基于文件的数组。 当我尝试在Statistics类中实例化此数组对象时,出现此错误:
错误:未报告的异常IOException; 必须被抓住或宣布被抛出
我同时抛出IOException和尝试捕获。 通过将try和catch放在action方法内部解决了类似的堆栈溢出问题,但是我的似乎已经拥有了。 任何帮助将非常感激。
UTIL:
import java.io.*;
import java.util.*;
import java.lang.*;
public class Util {
public static Student[] readFile(String fileName) throws IOException {
Student studentArray[]=new Student[15];
try{
FileReader file = new FileReader("studentData.txt");
BufferedReader buff = new BufferedReader(file);
String line;
line = buff.readLine();
int index=0;
while(line != null){
System.out.println(line);
if(index>14){
break;
}
line = buff.readLine();
String[] result = line.split("\\s");
int sid = Integer.parseInt(result[0]);
int scores[] = new int[5];
for(int x=1;x<result.length;x++){
scores[x-1] = Integer.parseInt(result[x]);
}
Student myCSC20Student = new Student(sid, scores);
studentArray[index++] = myCSC20Student;
}
}
catch (IOException e){
System.out.println("Error: " + e.toString());
}
return studentArray;
}
}
统计:
import java.io.*;
import java.util.*;
public class Statistics {
final int LABS = 5;
public int[] lowscores = new int[LABS];
private int[] highscores = new int[LABS];
private float[] avgscores = new float[LABS];
public static void main(String args[]) {
Student[] studArr = Util.readFile("studentData.txt") ;
System.out.println(studArr[1]);
}
void calculateLow(Student[] a){
}
void calculateHigh(Student[] a){
}
void calculateAvg(Student[] a){
}
}
您已将readFile
标记为readFile
IOException,因此,在使用该方法的任何地方,都需要将其包装在try-catch
块中。
对于您当前的代码,我建议删除该方法的throws
部分,因为无论如何您都在捕获它。 我建议您做的是删除方法中的try-catch
,然后将其留给调用方。 我推荐这样做是因为与返回的数组为空相比,它更容易捕获错误。
您已经在Util类中添加了try catch块,因此无需抛出IOException。 从Util类的readFile方法中删除throws子句。
readFile()声明IOException。 这意味着在调用它的任何地方,也必须声明IOException或捕获它。 在这种情况下,readFile()不需要声明IOException,因为它被捕获在方法中。
但是,更大的问题是您正在类初始化中调用面向IO的方法。 这使得很难理智地处理实际的异常。 至少,如果发生异常,您的readFile()应该返回null或空数组。
简而言之,不要在readFile()上声明IOException。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.