File.createNewFile():如何处理“未报告的异常”错误?

我是编程世界的新手。我正在上第六节课,我们受命使用File实例创建一个新文件。编译时出现io异常。我在网上搜索过,但似乎找不到可以理解的解释。


请多多包涵,但我的代码是:


import java.io.File;

public class TestFile{

  public static void main(String[] args) {

    File myArchive = new File("MyDocument.txt");

    boolean x = myArchive.createNewFile();

    System.out.println(x);

  }

}

据我了解,如果创建了文件,createNewFile()它将提供一个true值,但是我不断收到以下消息。


TestFile.java:5:错误:未报告的异常IOException; boolean x = myArchive.createNewFile();必须被捕获或被抛出。^ 1个错误


根据我在网上收集的信息,有一个例外需要捕获。教员没有建议如何处理代码异常或与命令try或catch。


非常感谢您的协助。如果我不遵守任何论坛的指南,请告诉我,这是我的第一篇文章,并且我还是编程的新手。


MM们
浏览 399回答 3
3回答

holdtom

在其中,java您将获得很多,Exceptions并且您必须使用try..catchblock来处理它。try{  //code that may throw exception  }catch(Exception_class_Name ref){}  另外,您必须boolean x 在try块之外进行定义,并且应将其初始化为某个值(true或false)。尝试以下代码:-import java.io.File;public class Main {  public static void main(String[] args) {    File myArchive = new File("MyDocument.txt");    boolean x = true;    try {      x = myArchive.createNewFile();    } catch (Exception e) {      e.printStackTrace();    }     System.out.println(x);  }}输出:-true

万千封印

只是一个尝试捕获的介绍,它的用途是:某些操作可能会产生错误,甚至可能不是程序员的错误,但可能由于不可预见的情况而发生。例如,您要创建一个文件,但是此时,文件目的地可能不存在(例如,取出了USB记忆棒),或者光盘可能已满,或者文件名可能无效(由另一个用户提供)通过键盘(包含“禁止”字符)进行操作,或者可能未授予权限(例如,在Android中,当您的手机要求写入文件的权限时,您可以授予它,或者出于安全考虑而拒绝授予它)。对于这种情况,Java为您提供了尝试容易出错的代码,然后捕获错误的机会。如果发生错误,则不希望您的应用崩溃。您希望它继续继续工作,因此您可以在屏幕上警告用户该文件操作失败,并提供其他操作。因此,基本上,您可以执行以下操作 try{   // place a risky part of code here   // like, creating a file } catch (Exception error) {     // This part will be executed only if there is an error     // in this part, you can change the wrong file name     // or tell the user that the disc is not available     // just do something about the error.     // If an error does not occur, then this part will not be executed.  } 

繁星点点滴滴

try {        boolean x = myArchive.createNewFile();        System.out.println(x);    } catch (IOException e) {        e.printStackTrace();    }try块包含可能发生异常的语句集。在try块之后始终是catch块,该catch块处理在关联的try块中发生的异常
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java