我正在通过一本书中的例子学习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);
}
}发布于 2016-03-18 04:00:04
因为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);
}
}发布于 2016-03-18 03:58:26
Files.createDirectory(Path dir, FileAttribute... attrs)抛出IOException,这是一个检查过的Exception;要么对其进行catch处理,要么修改main以指示可能会抛出它。就像,
public static void main(String[] args) throws IOException {或使用try-catch和catch (与IOException类似)
if(Files.notExists(dirPath)){
try {
Files.createDirectory(dirPath);
} catch (IOException e) {
e.printStackTrace();
}
} 发布于 2016-03-18 04:00:23
查找一个尝试捕获,并将处理文件的代码部分放入其中。如果无法创建文件或该位置不存在,这将处理和报告异常。
https://stackoverflow.com/questions/36075831
复制相似问题