我正在通过书中的示例学习 Java。 我写了下面的代码并得到“未处理的异常类型 IOException” 为什么?我该如何解决这个问题。我应该声明 IOException 类吗?
import java.nio.file.*;
public class JavaIO {
public static void main(String[] args) {
String dirString = "C:/Users/USER/Desktop/Test/Files";
Path dirPath = Paths.get(dirString);
if(Files.notExists(dirPath)){
Files.createDirectory(dirPath);
}
System.out.println("Err");
System.exit(1);
}
}
最佳答案
因为Files.createDirectory()
可能会抛出java.io.IOException
,而您既没有捕获它也没有声明抛出它。
捕获异常来处理错误
import java.nio.file.*;
public class JavaIO {
public static void main(String[] args) {
String dirString = "C:/Users/USER/Desktop/Test/Files";
Path dirPath = Paths.get(dirString);
if(Files.notExists(dirPath)){
try{
Files.createDirectory(dirPath);
} catch(java.io.IOException e){
System.out.println("createDirectory failed:" + e);
}
}
System.out.println("Err");
System.exit(1);
}
}
或者添加声明来抛出它,以忽略它被抛出的可能性。
import java.nio.file.*;
public class JavaIO {
public static void main(String[] args) throws java.io.IOException {
String dirString = "C:/Users/USER/Desktop/Test/Files";
Path dirPath = Paths.get(dirString);
if(Files.notExists(dirPath)){
Files.createDirectory(dirPath);
}
System.out.println("Err");
System.exit(1);
}
}
关于java - 为什么我得到 "Unhandled exception type IOException",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36075831/