为什么我得到“未处理的异常类型IOException”

时间:2016-03-18 03:54:09

标签: java exception-handling io

我正在通过书中的例子来学习Java。 我在下面写了代码,得到了“Unhandled exception type 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);
    }
}

4 个答案:

答案 0 :(得分:4)

因为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);
    }
}

答案 1 :(得分:3)

Files.createDirectory(Path dir, FileAttribute<?>... attrs)抛出IOException,这是已检查 Exception; catch或修改main以表明可能被抛出。像,

public static void main(String[] args) throws IOException {

使用try-catchcatch IOException

if(Files.notExists(dirPath)){
    try {
        Files.createDirectory(dirPath);
    } catch (IOException e) {
        e.printStackTrace();
    }
 }   

答案 2 :(得分:0)

查找Try Catch并将代码中处理该文件的部分放在其中。如果无法创建文件或位置不存在,这将处理并报告异常。

答案 3 :(得分:0)

当您使用Java处理文件或执行IO操作时,由于各种原因,您可能无法访问文件或资源,这将在FIleNotFound或IO操作行引发异常条件无法执行。需要处理此异常,因为它在Java中的“已检查”异常下进行。简单地说你需要自己处理这个案例,或者让子类使用Throws,throw或try / catch块来完成它。

因此,对于“未处理的异常类型IOException”消息,Java要求您执行相同的操作。

相关问题