【问题标题】:I need to use a try-catch, but it says it is an unreachable catch block. How do I make it reachable?我需要使用 try-catch,但它说这是一个无法访问的 catch 块。我如何使它可以访问?
【发布时间】:2019-02-10 17:50:07
【问题描述】:

我是编码新手,对java也很陌生,所以请多多包涵,对不起。

我的教授说我们需要使用以下代码作为我们作业的一部分。我查看了课堂上的所有笔记,但在 try-catch 中找不到任何内容,我不确定应该在插入代码部分中输入什么或错误消息的含义

我很抱歉,我只是很困惑。我不断得到 “FileNotFoundException 的无法到达的 catch 块。这个异常永远不会从 try 语句体中抛出” 我不知道如何解决它

try 
{
    File file = new File( args [ 0 ] );
    Scanner scanner = new Scanner( file );

    //insert code

    scanner.close();
}
catch  (FileNotFoundException e)
{
 e.printStackTrace();
}

编辑:在我尝试对文本文件进行硬编码以进行测试之前,我在修复它之后没有再次收到该错误。

try 
{
    File file = new File( args [ 0 ] );
    Scanner scanner = new Scanner("cat.txt");

    //insert code

    scanner.close();
}
catch  (FileNotFoundException e)
{
 e.printStackTrace();
}

我再次收到“FileNotFoundException 无法到达的 catch 块。这个异常永远不会从 try 语句体中抛出”

我应该在 try 语句中添加什么?我很迷茫

【问题讨论】:

  • 您的Scanner 声明中缺少分号。
  • 您列出的错误绝对不是您引用的代码引起的。 FileNotFoundException 确实是由new Scanner(File) 抛出的。您引用的代码不会因为 不同 的原因编译(在 new Scanner(file) 之后缺少 ;),但不是因为该块没有抛出 FileNotFoundException。也许你有一个不同的块,你没有展示它的代码永远不会抛出异常......?
  • 你好,我编辑了它,我不再有那个错误,但是现在当我运行我的代码时,我得到“线程中的异常”main”java.lang.ArrayIndexOutOfBoundsException:索引 0 超出范围在模板中长度为 0.SentenceUtilsTest.main(SentenceUtilsTest.java:26)"
  • 在执行代码时需要将文件名或路径作为 JVM 参数传递。例如java Myclass .

标签: java try-catch filenotfoundexception


【解决方案1】:

在我尝试对文本文件进行硬编码以进行测试之前,修复它后我没有再次收到该错误。

try 
{
    File file = new File( args [ 0 ] );
    Scanner scanner = new Scanner("cat.txt");

    //insert code

    scanner.close();
}
catch  (FileNotFoundException e)
{
 e.printStackTrace();
}

我再次收到“FileNotFoundException 无法到达的 catch 块。

new Scanner(String)new Scanner(File) 不同。如果您查看文档,第一个(使用String)读取从字符串,而不是从文件。由于不涉及文件,因此没有FileNotFoundException

如果您想对文件名进行硬编码以进行测试,请在 new File(...) 行中执行此操作,而不是在 new Scanner(...) 行中:

try 
{
    File file = new File("cat.txt");      // <==== Here
    Scanner scanner = new Scanner(file);

    //insert code

    scanner.close();
}
catch (FileNotFoundException e)
{
    e.printStackTrace();
}

这将编译,因为new Scanner(File) 抛出FileNotFoundException

【讨论】:

  • 谢谢!我现在遇到了一个不同的错误,我可能只是发布一个单独的问题,但我认为我应该在 try 语句中添加更多代码,但我不确定是什么。当我编译代码时,我得到“线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException:Index 0 out of bounds for length 0 at templates.SentenceUtilsTest.main(SentenceUtilsTest.java:26)”
【解决方案2】:

欢迎来到 SO!异常是捕获错误并决定如何处理它们的好方法。某些代码段要求程序飞跃并尝试执行当时可能无法执行的任务。

问题中指定的错误是扫描程序未在指定文件路径中找到文件的结果。 ArrayIndexOutOfBounds 准确地指示异常状态。正在访问的索引超出了数组的边界(大小)。

Java 文档是一个很好的资源,它应该有助于阐明 catch 语句的目的。 https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    • 2016-12-25
    • 2014-10-26
    • 2018-03-20
    • 1970-01-01
    • 2013-02-08
    • 2019-08-06
    相关资源
    最近更新 更多