如何调试try和catch块?

时间:2016-11-05 19:21:58

标签: java try-catch throw catch-block

我想知道是否有人可以用Java帮助我完成这两个调试任务,包括try / catch / throw语句。我似乎无法弄清楚如何调试在NetBeans Zip文件中工作的任务。

感谢所有或任何帮助。 感谢。

作业1:

package debugmeone;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/*
 * This file requires debugging.  This is a partial file to read a text file
 * with simple error checking.  If the file is not found (you are testing this)
 * a FileNotFoundException should be thrown.  The second catch statement is
 * producing an error (red stop sign).  Why?  Your job is to have both
 * Exception and FileNotFoundException in this file.  Do not remove either one
 * of them.  Don't create the file accountrecords.txt; you are testing for
 * a file not found condition so there is no need to create the file.
 *
 * The output should be:
 *
 *   run:
 *   Error - File Not Found: accountrecords.txt
 *   Java Result: 100
 *   BUILD SUCCESSFUL (total time: 0 seconds)
 */

public class ReadTextFile {

    private Scanner input;  // Ignore the hint given by NetBeans

    public void openFile() {
        try
        {
            input = new Scanner( new File("accountrecords.txt"));
        }
        catch(Exception e)
        {
            System.out.println("Something bad just happened here.");
            System.exit(707);
        }
        // Debug this line; what should you do to solve this error message?
        //   Carefully read the error message provided by the IDE
        catch( FileNotFoundException  fnfe)
        {
            System.out.println("Error - File Not Found: accountrecords.txt");
            System.exit(100);
        }
    }
}

作业2:

package debugmetwo;

/*
* You will need to debug this file.
*
* The output should be:
*
*  run:
*  There is a problem with the Eagle!
*  Java Result: 9999
*  BUILD SUCCESSFUL (total time: 0 seconds)
*/
public class ThrowEagleExceptionTest {

    public static void main(String[] args) {
        try {
         EagleLanding();
        } catch (EagleLandingException badEagle) {
            System.out.printf("%s\n", badEagle.getMessage());
            System.exit(9999);
        }
    }

    private static void EagleLanding {
         EagleLandingException("There is a problem with the Eagle!");
    }
}

1 个答案:

答案 0 :(得分:1)

您有一个编译时错误消息,而不是调试器的运行时错误消息。要阅读的信息是

    // Debug this line; what should you do to solve this error message?
    //   Carefully read the error message provided by the IDE
    catch( FileNotFoundException  fnfe)

您需要阅读IDE中提供的错误消息并进行修复。提示:最具体的例外必须先行。

你的第二个例子也不会编译。你需要通过抛出异常来进行编译。如果你不知道如何做到这一点,请看一个例​​子。