【问题标题】:How to correctly use try-catch-finally blocks in Java?如何在 Java 中正确使用 try-catch-finally 块?
【发布时间】:2015-10-06 16:19:53
【问题描述】:

使用 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.");      
}

【问题讨论】:

  • 您是否遇到任何错误?如果有,它们是什么?
  • @NikG 这些是我收到的错误: 线程“main”中的异常 java.lang.IllegalStateException: Scanner closed at java.util.Scanner.ensureOpen(Scanner.java:1070) at java .util.Scanner.hasNext(Scanner.java:1334) 在 gironjavaassn6.GironJavaAssn6.main(GironJavaAssn6.java:35)

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


【解决方案1】:

扫描仪应该是这样工作的:

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

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

【讨论】:

  • 你太棒了!我将 finally 块的内容放在 while 外观之外(甚至不需要 finally 块)并且它起作用了!非常感谢!非常感谢您今天的帮助!
  • 当然是尤尔根。总是那么简单的事情让我着迷。再次感谢您的帮助。
  • 这是我的第一篇文章,我不知道我不能接受超过一个人的回复。你的第一个也是正确的,所以你应得的:)
【解决方案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,你的程序应该恢复正常。

您还可以将 while 循环移到 try 块内,这也可以。

【讨论】:

  • 谢谢 Psychrom!这非常有用,有助于纠正我的代码。小事总是让我着迷。无论如何,我非常感谢您抽出宝贵时间提供帮助,谢谢。
【解决方案3】:

你需要在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 语法并将流的关闭留给 jvm。

【讨论】:

  • 从字面上看是对的,但您不必关闭文件。
  • @Afsin 是的,但最好明确开发者的意图。所以我为什么要明确表示。
  • 感谢您的回复 Davide,原来我在 while 循环中有 finally 块。因此,如果循环读取“没有更多行可读取 - 退出循环”,它将永远不会到达 finally 块。我将 finally 循环的内容放在 while 循环之外,它起作用了。感谢您的宝贵时间!
猜你喜欢
  • 1970-01-01
  • 2015-09-05
  • 2011-06-01
  • 2012-02-07
  • 2021-03-29
  • 2011-11-17
  • 2011-10-31
  • 2013-12-16
  • 1970-01-01
相关资源
最近更新 更多