Java 为什么我得到了;未处理的异常类型IOException“;
我正在通过书中的例子学习Java。 我写了下面的代码,得到了“未处理的异常类型IOException” 为什么?我怎样才能解决这个问题。我应该声明IOException类吗Java 为什么我得到了;未处理的异常类型IOException“;,java,exception-handling,io,Java,Exception Handling,Io,我正在通过书中的例子学习Java。 我写了下面的代码,得到了“未处理的异常类型IOException” 为什么?我怎样才能解决这个问题。我应该声明IOException类吗 import java.nio.file.*; public class JavaIO { public static void main(String[] args) { String dirString = "C:/Users/USER/Desktop/Test/Files";
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);
}
}
抛出被选中的异常
;catch
it或modifymain
以指示可能会抛出它。大概
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();
}
}
因为
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);
}
}
查找Try-Catch,并将处理该文件的代码部分放在其中。如果无法创建文件或位置不存在,这将处理并报告异常情况。当您使用文件或在Java中执行IO操作时,可能由于各种原因无法访问文件或资源,这将在FIleNotFound或IO操作无法执行的行上引发异常条件。这个异常需要处理,因为它在Java中属于“checked”异常。简单地说,您需要自己处理这种情况,或者让子类使用Throws、throw或try/catch块来处理
因此,Java会发出“Unhandled exception type IOException”消息,要求您也这样做。这很可能是因为您尚未创建指向“文件”的目录,请改用“CreateDirectory”。谢谢!!!!!!我添加了try-catch语句,但仍然出现错误。我使用java.io.IOException而不是IOException。非常感谢。非常感谢。我添加了try-catch语句,但仍然出现错误。我使用java.io.IOException而不是IOException。非常感谢。哦,这只是意味着如果你想在程序中写得更短,就必须导入java.io.IOException。谢谢!!!!!!我添加了try-catch语句,但仍然出现错误。我使用java.io.IOException而不是IOException。谢谢@pty115添加
import java.io.IOException代码>并且不需要完全限定类名。那么我应该处理JAVA中所有可能的异常吗?在其他编程语言中,我不需要这样做。它是JAVA的特征吗?不是所有的,只是你被要求的那个,有一个通过使用Exception类来捕获所有的方法,这是所有“checked”异常的父类。