gpt4 book ai didi

java - 需要针对 Java 中的这段代码进行澄清

转载 作者:行者123 更新时间:2023-12-02 00:50:20 26 4
gpt4 key购买 nike

当我写下这篇文章时

String path="d:\\test.txt";
boolean chk;
File f=new File(path);

try
{
chk=f.createNewFile();
}catch(IOException e)
{
chk=false;
e.printStackTrace();
}


if(chk)
System.out.println("file created.");
else
System.out.println("file not created");

文件已在 D 驱动器中创建

但是当我使用这个

String path="d:\\test.txt";
File f=new File(path);

if(f.createNewFile())
System.out.println("file created.");
else
System.out.println("file not created");

它抛出异常。

请赐教一下

最佳答案

我怀疑第二段代码是否真的“抛出异常”;您看到的很可能是一个编译错误,警告您在调用 createNewFile 时必须捕获已检查的异常 IOException

“已检查”异常必须具有处理程序或由调用方法通过抛出声明,否则您的代码将无法编译。检查IOExceptioncreateNewFile 声明它抛出 IOException。因此您的第二个代码块不正确。

关于java - 需要针对 Java 中的这段代码进行澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3482141/

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