VM 在静态方法上终止

VM Terminated on static method

public static void main()     {
   String fileName = "cardNumbers.txt";
   String line = null;
   try {
       FileReader fileReader = new FileReader(fileName);
       BufferedReader bufferedReader = new BufferedReader(fileReader);
       while((line = bufferedReader.readLine()) != null)
       {
           CreditCard card = new CreditCard(line);
           if (card.creditCardType().equalsIgnoreCase("Unknown"))
           {
               System.out.println("Card number " + card.getCardNumber() + "is an unknown credit card type.");
            }
            else if (card.isValid())
            {
                System.out.println(card.creditCardType() + " number" + card.getCardNumber() + " is valid.");
            }
            else if (!card.isValid())
            {
                System.out.println(card.creditCardType() + " number " + card.getCardNumber() + " is not valid.");
            }
        }
    }
   catch (FileNotFoundException ex)
   {
       System.out.println("file not found exception thrown");
    }
    catch (IOException ex)
    {
        System.out.println("error while reading the file");
    }
    finally
    {
        System.exit(0);
    }
}

当我 运行 这个方法时,它只是说 ProcessCardNumbers.main(); VM Terminated. 而不是实际打印出内容。

如果我在函数的开头或 finally 块中添加打印,它们将被打印出来。

我不确定为什么会这样或者我该如何解决它。

您的主要方法签名必须如下所示:

public static void main(String[] args)

而不是

public static void main()

这似乎在您的文本文件中 cardNumbers.txt 没有数据。当此程序将在 while 循环内执行时 bufferedReader.readLine())。将 return null。所以循环将终止。终止后,您在 finally 块中编写了 System.exit(0); 函数,当场终止 JVM。所以 JVM 现在已终止,这就是为什么在运行此代码后您看不到任何内容的原因。

如果要检查工作,在finally块中写一个SOP语句。可能会在不终止 JVM 的情况下执行。

正如您告诉我们的那样:

Adding a println at the start is printed

Adding a println in the finally works too

我们可以推断您的代码正在运行。只是当你到达 while((line = bufferedReader.readLine()) != null) 时,线路停留在 null,所以你永远不会进入你的 while。

这是为什么?好吧,您的文件一开始可能是空的。如果不是,请仔细检查文件的编码:它可能没有使用正确的 returns 符号,因此没有 "completed line".

这里的问题不是你的代码有bug,而是没有让你看到bug的设计问题。

您可能遇到未声明的异常 (RuntimeException) 并且 VM 无法打印它,因为您之前在 finally 中将其终止。

您有多种选择:

  1. 去掉System.exit(0);让它正常死去。如果有另一个非守护线程 运行,这可能会失败。你可以试着阻止它。例如,您可以 cancel a Timer.

  2. finally 之前添加一个 catch (RuntimeException e) { 部分并打印捕获的错误。 e.printStackTrace(); 应该可以解决问题。

对于其中任何一个,您应该会在控制台上看到异常,以便您可以修复它。