我被要求将带有throw异常IF的代码转换为try / catch块。我已经设置了但是我不知道该用什么来代替输出这个词以便它可以运行。我不确定在读完书和oracles信息后试试看/我看到了需要做什么,所以txt文件会打印出来。我将发布要修改的代码,然后使用try / catch进行更改。谢谢你的帮助。
public class WriteData {
public static void main(String[] args) throws Exception {
java.io.File file = new java.io.File("scores.txt");
if (file.exists()) {
System.out.println("File already exists");
System.exit(0);
}
// Create a file
java.io.PrintWriter output = new java.io.PrintWriter(file);
// Write formatted output to the file
output.print("John T Smith ");
output.println(90);
output.print("Eric K Jones ");
output.println(85);
// Close the file
output.close();
}
}
以下是为Try / Catch
更改的代码import java.io.FileNotFoundException;
public class WriteData {
public static void main(String[] args) {
java.io.File file = new java.io.File("scores.txt");
try {
output = new java.io.PrintWriter(file);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
// Create a file
java.io.PrintWriter output = new java.io.PrintWriter(file);
// Write formatted output to the file
output.print("John T Smith ");
output.println(90);
output.print("Eric K Jones ");
output.println(85);
// Close the file
output.close();
}
}
答案 0 :(得分:1)
进行这些更正后,您的代码应如下所示:
import java.io.*;
public class WriteData {
public static void main(String[] args) {
File file = null;
PrintWriter output = null;
try
{
file = new File("scores.txt");
output = new PrintWriter(file);
output.print("John T Smith ");
output.println(90);
output.print("Eric K Jones ");
output.println(85);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
finally
{
//The output not be instanciated if scores.txt was not found.
if(output != null)
output.close();
}
}
}
在我看来,这是处理你案件的最好办法。
答案 1 :(得分:0)
try {
output = new java.io.PrintWriter(file); // output is not defined yet
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
// Create a file
// This one will throw the FileNotFoundException
java.io.PrintWriter output = new java.io.PrintWriter(file);
您可以像这样修改
try {
java.io.PrintWriter output = new java.io.PrintWriter(file);
//rest of the code
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
答案 2 :(得分:0)
您的错误:
从jean-FrançoisSavard的解决方案中删除IoException的catch块。
FileNotFoundException是PrintWriter()抛出的已检查异常。作为一种做法,只捕获API签名中声明的异常。
(事实上保持任何一个块都可以工作,因为FileNotFoundException扩展了IOException)