在Java中显示正确的输出之前显示错误消息

时间:2013-11-16 22:30:30

标签: java

我正在实现一个try catch块来确认文件存在,然后再从文件中读取数据,然后使用该数据打印出一个菜单,最终运行一个菜单驱动的应用程序。看起来好像我正在从文件中读取,但是,当我运行驱动程序类时,它会在正确显示输出菜单之前显示catch块中包含的错误消息。

public static void main(String[] args)

{
    try
    {
        Scanner input = new Scanner(new File("concerts.txt"));
        ConcertEvent concert1 = new ConcertEvent(input);
        ConcertEvent concert2 = new ConcertEvent(input);
        ConcertEvent concert3 = new ConcertEvent(input);


        System.out.println("Redbird Concert Hall");
        System.out.println();
        System.out.println("Please choose your concert:");
        System.out.println("1. " + concert1.getBandName());
        System.out.println("2. " + concert2.getBandName());
        System.out.println("3. " + concert3.getBandName());
        System.out.println("4. Quit");
        System.out.println();
    }
    catch(Exception e)
    {
        System.out.println("Error: File Not Found");
    }

我附加了用于创建ConcertEvent的三个实例的构造函数

public ConcertEvent(Scanner input)
{
    try
    {
        bandName = input.nextLine();
        showCapacity = input.nextInt();
        ticketPrice = input.nextDouble();
        input.nextLine();
    }
    catch(Exception e)
    {
        System.out.println("Error: file not found");
    }

}

期望的输出:

Redbird Concert Hall

Please choose your concert:
1. Maroon 5
2. One Direction
3. Pearl Jam
4. Quit

实际输出:

Error: file not found (Exception found in the catch statement of the 
Redbird Concert Hall

Please choose your concert:
1. Maroon 5
2. One Direction
3. Pearl Jam
4. Quit

我意识到在构造函数中使用try catch块可能不正确,但是当我删除try catch块时,实际输出更改为...

错误:找不到文件(在main方法的catch语句中找到异常)

1 个答案:

答案 0 :(得分:1)

触发的catch块是ConcertEvent构造函数中的块,可能是文件无法找到或无法访问,或者等等。(在打印之前你不会知道)堆栈跟踪)。

如果您希望在任何文件操作之前进行提示输出,只需将其移至try方法中的main块之前。

此外,正如Chandranshu所提到的,捕捉特定的例外情况将有助于您解决问题。

最后,让main方法为同样具有try / {{的构造函数声明catch / try语句没有多大意义1}}语句,合理地用于相同的catch(s)。

构造函数中的Exception throw,或者Exception方法中的try / catch

例如,由于main是已检查的例外,您可以在构造函数中FileNotFoundException(并且必须在其签名中声明throw语句) ,然后在throwscatch,然后在main中的printStackTrace语句中catch。{/ p>