PrintStackTrace导致我的程序崩溃。为什么?

时间:2018-05-04 21:07:22

标签: java eclipse printstacktrace

我制作了一些简单的代码,它应该运行得很好。问题是,它没有。我花了一些时间来弄清楚数字格式异常的原因是什么。显然,当我尝试输入字母而不是数字时,它应该让我重新输入它,但它会崩溃。但是当我删除e.printStackTrace();它的工作正常。有人可以告诉我为什么吗?

import java.util.Scanner;

public class Test {

public static boolean isInteger(String strNumber) {
    try {
        int number = Integer.parseInt(strNumber);
        if(number > 0) {
            return true;
        }
        return false;
    } catch (NumberFormatException e) {
        e.printStackTrace();

        return false;
    }

}

public static void main(String[] args) {

    String numberString = null;
    int number = 0;
    Scanner scanner = new Scanner(System.in);
    do {
        System.out.println("Enter integer:");
        numberString = scanner.nextLine();

    }   while(!isInteger(numberString));

       number = Integer.parseInt(numberString);
       System.out.println("Your number is: " + number);
       scanner.close();
   }

}

1 个答案:

答案 0 :(得分:2)

我相信您的程序仍在运行。如果未捕获异常,e.printStackTrace()将显示与程序相同的输出。 例如:

`java.lang.NumberFormatException: For input string: "asdf"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at Test.isInteger(Test.java:7)
    at Test.main(Test.java:29)`

此外,您可能在调试输出后看不到"Enter integer: ",因为它发送到的流System.err与常规打印流System.out是分开的。这意味着有时,对System.err和System.out的打印总是以与调用它们相同的顺序出现。

所有这一切都是说您的程序可能仍在运行。它只是看起来像一个崩溃,因为e.printStackTrace()打印出一个导致崩溃的未捕获异常时会得到的相同信息。

相关问题