這裏是我的代碼:我得到一個錯誤:「異常FileNotFoundException異常在相應try語句的身體從來沒有拋出」,不能弄清楚爲什麼
import java.util.Scanner;
import java.io.*;
public class Warning
{
public static void main (String[] args)throws IOException
{
int creditHrs;
double qualityPts;
double gpa;
String name;
// Set up scanner to input file
Scanner inFile = new Scanner(new File("c:\\students.dat"));
System.out.println ("\n Students on Academic Warning\n");
// Process the input file, one token at a time
try
{
while (inFile.hasNext())
{
// Get the credit hours and quality points and
// determine if the student is on warning. If so,
// display the student's name.
name = inFile.next();
creditHrs = Integer.parseInt(inFile.next());
qualityPts = Double.parseDouble(inFile.next());
gpa = qualityPts/creditHrs;
if(gpa < 2.0)
{
System.out.println(name);
}
}
}
//insert catch statements
catch(FileNotFoundException e)
{
}
catch(NumberFormatException e)
{
}
inFile.close();
}
}
的錯誤是:錯誤:異常FileNotFoundException異常是永遠扔在相應的試語句中 爲什麼我得到這個?我認爲它不會拋出異常是一件好事,爲什麼它必須告訴我,你知道嗎?我真的不明白這
[異常從不會在相應的try語句的主體中拋出]可能的重複(http://stackoverflow.com/questions/22613423/exception-is-never-thrown-in-body-of-corresponding-try-statement ) – andersschuller
當您嘗試打開文件並且找不到文件時,會發生'FileNotFoundException'。在嘗試打開文件的'try'塊中沒有任何內容,只有讀取文件的代碼。要麼你在捕捉錯誤的異常,要麼在你的'try'塊上面有一些文件打開語句,這些語句可能應該被移除。或者'catch(FileNotFoundException e)'塊從其他程序中跳入。 – ajb