我正在编写一个使用IOExceptions的程序,而且我遇到了一个我无法弄清楚的错误。代码是
主:
public class IOJ {
public static void main(String[] args) {
findStuff calc = new findStuff();
calc.findSyl();
//^ Unreported exception IOException, must be caught or declared to be thrown
calc.printRes();
}
}
以及投掷的实际文件
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.StringTokenizer;
public class findStuff {
private double findSyl; //find Syl
private double printRes; //print results
public double NumSylG = 0; //number of syllables
public double findSyl()throws IOException {
BufferedReader inputStream = null;
PrintWriter outputStream = null;
try {
String newLine = "";
outputStream.println(newLine);
String[] tokens = newLine.split(" ");
char temp;
for (int i = 0; i < newLine.length(); i++) {
temp = newLine.charAt( i );
if (Character.isLetter(temp) )
NumSylG++;
}
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} finally {
if (inputStream != null)
inputStream.close();
if (outputStream != null)
outputStream.close();
}
return findSyl;
}
public double printRes() {
System.out.printf("The total number of Syl in Gettysburg is: %.1f \n", NumSylG);
return printRes;
}
}
findStuff
文件编译得很好。当我从main调用它时,我得到了那个错误。
我仍然习惯于捕捉和扔东西所以任何人都能给我一些关于我做错的见解吗?注意:出于隐私原因,我没有放置文件路径。
答案 0 :(得分:0)
public double findSyl()throws IOException
findSyl()
声明它抛出IOException
,这是一个经过检查的异常。这意味着findSyl()
的调用者必须捕获该异常或声明它也可能抛出该异常。
您有两个选择:
1
public static void main(String[] args)
{
findStuff calc = new findStuff();
try {
calc.findSyl();
calc.printRes();
}
catch (IOException ex) {
// handle the exception here
}
}
2
public static void main(String[] args) throws IOException
{
findStuff calc = new findStuff();
calc.findSyl();
calc.printRes();
}