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

标签 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();
   }

}

最佳答案

我相信你的程序仍在运行。 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)`

此外,您可能在调试输出后看不到 “输入整数:”,因为它发送到的流 System.err 是分开的System.out,常规打印流。这意味着有时,System.err 和 System.out 的打印并不总是按照调用它们的顺序出现。

所有这些都表明您的程序可能仍在运行。它看起来像是崩溃,因为 e.printStackTrace() 打印的信息与在未捕获的异常导致崩溃时获得的信息相同。

关于java - PrintStackTrace 导致我的程序崩溃。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50183059/

相关文章:

java - Android OpenGLES 在 GLThread 中加载纹理然后告诉 UI 线程运行一个方法

java - 如果我已经安装了 JDK 和 JRE,是否需要安装 Eclipse Neon 的 Java 插件?

java - 为 Runnable Jars 使用不同的属性文件,Maven Eclipse

python - 改进 python 中的堆栈跟踪钩子(Hook)

java - Spring + Spring Security + Hibernate org.springframework.aop.config.AopNamespaceUtils.registerAutoProxyCreatorIfNecessary

java - Hadoop 给 reducer 带来了什么?

java - 运行jdbc时出错

c++ - 将 libpng 链接到 android 原生项目

java - 将异常的堆栈跟踪转换为 byte[] 数组或 ByteBuffer (Java) 是否更有效?