簡體   English   中英

在Java中顯示正確輸出之前顯示錯誤消息

[英]Error message being displayed before correct output shown in 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語句中找到異常)

觸發的catch塊是ConcertEvent構造函數中的catch塊,可能是找不到或無法訪問該文件等。(在打印堆棧跟蹤之前,您不會知道)。

如果您希望在任何文件操作之前進行提示輸出,只需將其移至main方法中try塊之前即可。

另外,正如Chandranshu所提到的,捕獲特定的異常將幫助您確定問題所在。

最后,讓您的main方法為也有try / catch語句的構造函數聲明try / catch語句並沒有多大意義,對於相同的Exception ,是合理的。

可以在構造函數中throw Exception ,或者在main方法中刪除try / catch

例如,作為FileNotFoundException是一個checked異常,你可以throw在你的構造它( 必須聲明throws在其簽名語句),然后catch它在main ,那么printStackTracecatch聲明中main )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM