如何在Java中正确使用try-catch-finally块?

时间:2015-10-06 16:19:54

标签: java try-catch fstream instantiation try-catch-finally

使用finally块关闭我所在文件的正确方法是什么:event.dat。如果你能帮我理解这一点,我会非常感激。我花了4个小时搬东西,玩代码并在网上搜索答案,但无济于事。代码在没有该部分的情况下工作得很好,但我需要知道它如何适用于未来的实例。谢谢你,有一个美好的一天!

我遇到了这个问题:

          finally{
              fstream.close();        
          } 

位于以下代码中:

    String answer;
    String letter;
    String inType = "";
    double inAmount = 0;
    double amount;

    description();
    GironEventClass newInput = new GironEventClass();
    try{
        File infile = new File("event.dat");
        Scanner fstream = new Scanner(infile);

        System.out.println("File Contents ");

        while(fstream.hasNext())
        {
            inAmount = fstream.nextInt();
            inType = fstream.next();

            try{
                newInput.donations(inType, inAmount);

            }
            catch(IllegalArgumentException a){
                System.out.println("Just caught an illegal argument exception. ");
            }  
           finally{
                   fstream.close();        
          }  
        }

        System.out.println("Total Sales: " + newInput.getSale());
        System.out.println("Donations: " + newInput.getDonated());
        System.out.println("Expenses: " + newInput.getExpenses());



    }

    catch (FileNotFoundException e){
        System.out.println("\nEvent.dat could not be opened. ");
    }

    do{
        System.out.print("Are there any more items to add that were not in the text file? (Type 'Y' or 'N')");
        answer = keyboard.next();
        if (("Y".equals(answer)) || ("y".equals(answer)))
        {
            letter = inLetter();
            amount = inAmount();

            newInput.donations(letter, amount);
        }

    }while (("Y".equals(answer)) || ("y".equals(answer)));

    newInput.display();
}

public static String inLetter(){
    Scanner keyboard = new Scanner(System.in);
    String result;
    String resultTwo;

    System.out.println("T = Tiket Sales");
    System.out.println("D = Donations");
    System.out.println("E = Expenses");
    System.out.print("Please input an identifier ");
    result = keyboard.nextLine();
    resultTwo = result.toUpperCase();

    return resultTwo;    
}

public static double inAmount(){
    Scanner keyboard = new Scanner(System.in);
    double result;

    System.out.println("Please input an amount ");
    result = keyboard.nextInt();

    if(result <= 0.0){
        System.out.print("Please input a positive and non-zero amount ");
        result = keyboard.nextInt();
    }

    return result;
}

public static void description(){
    System.out.println("The program will ask you what amount is being spent on what.");
    System.out.println("    ex: expenses, ticket sales, and profts.");
    System.out.println("This program will help determine whether the event generated or lost money.");      
}

3 个答案:

答案 0 :(得分:2)

扫描仪应该如何工作:

while scanner has object
   read them ( one object per method's call) 
when objects are done
   close the reader.

你的问题是当while结论为真时你使用close函数。所以你应该把它放在while循环之外

答案 1 :(得分:2)

The Try block尝试做某事。

The Catch block仅在Try块期间出现问题时执行。

The Finally block在Try块(和Catch块,如果执行)之后执行每次。

您的问题是您尝试在while循环中关闭fstream。

while(fstream.hasNext())  <----- referencing fstream
        {
            inAmount = fstream.nextInt();
            inType = fstream.next();

            try{
                newInput.donations(inType, inAmount);

            }
            catch(IllegalArgumentException a){
                System.out.println("Just caught an illegal argument exception. ");
            }  
           finally{
                   fstream.close();        <---- closing said stream
          }  
        }

由于你已经关闭了流,这个while循环应该只执行一次。话虽这么说,关闭while循环外的fstream,你的程序应该恢复正常。

你也可以在try块中移动while循环,这也可以。

答案 2 :(得分:-1)

你需要在try块之外声明fstream,否则它将在finally块中不可见。

File infile = null;
File infile = null;
try {
    infile = new File("event.dat");
    fstream = new Scanner(infile);

    ...
} catch ( ) {
    ...
} finally {
   // You need to handle exceptions also here
   infile.close();
   fstream.close();
}

您还可以使用新的try with resources语法,并将jtm保留为流的闭包。