gpt4 book ai didi

Java 文件异常处理

转载 作者:行者123 更新时间:2023-12-01 06:29:49 25 4
gpt4 key购买 nike

我应该为我的 java 作业创建一个示例程序,用于文件操作的异常处理。因为我是 C++ 人员,所以我很难理解。如果有人能指出我下面代码中的缺陷,那将非常有帮助。我指的是this文章。 Eclipse 给我“FileNotFoundException 无法访问的 catch block 。try 语句主体永远不会抛出此异常” 错误。

import java.io.*;

public class file {

public static void main(String[] args) {
String arg1 = args[0];
String arg2 = args[1];
System.out.println(arg1);
System.out.println(arg2);
File f1, f2;

try {
f2 = new File(arg2);
f1 = new File(arg1);
}
catch(FileNotFoundException e) {
/*
if(!f1.exists()) {
System.out.println(arg1 + " does not exist!");
System.exit(0);
}
if(!f2.exists()) {
System.out.println(arg2 + " does not exist!");
System.exit(0);
}


if(f1.isDirectory()) {
System.out.println(arg1 + " is a Directory!");
System.exit(0);
}
if(f2.isDirectory()) {
System.out.println(arg2 + " is a Directory!");
System.exit(0);
}

if(!f1.canRead()) {
System.out.println(arg1 + " is not readable!");
System.exit(0);
}
if(!f2.canRead()) {
System.out.println(arg2 + " is not readable!");
System.exit(0);
}*/
}
}
}

最佳答案

查看 File constructor you're calling 的文档。它声明抛出的唯一异常是NullPointerException。因此它不能抛出FileNotFoundException,这就是您收到错误的原因。您不能 try catch 编译器可以证明永远不会在相应的 try block 内抛出的已检查异常。

创建File对象不会检查其存在。如果您打开文件(例如使用new FileInputStream(...)),那么可能会抛出FileNotFoundException。 ..但不仅仅是创建一个 File 对象。

关于Java 文件异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13256285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com