Java异常:为什么我的程序没有终止?

Java异常:为什么我的程序没有终止?,java,exception,Java,Exception,当我运行简单的代码并输入字符而不是应该输入的整数值时。 下面列出的程序应在打印后终止。“错误请输入整数值” 但此代码在出现错误后也会打印该行 import java.util.InputMismatchException; import java.util.Scanner; public class Test { public static void main(String[] args) { System.out.println("enter value integ

当我运行简单的代码并输入字符而不是应该输入的整数值时。 下面列出的程序应在打印后终止。“错误请输入整数值”

但此代码在出现错误后也会打印该行

import java.util.InputMismatchException;
import java.util.Scanner;

public class Test { 
    public static void main(String[] args) {
        System.out.println("enter value integer ");
        Scanner sn = new Scanner(System.in);
        try{
            int a = sn.nextInt();
        } catch (InputMismatchException ex){
            System.out.println("error please enter integer value");
        }
        System.out.println("not terminating");
    }
}

它正在终止,它只是先打印出系统。这是意料之中的-它跳入捕捉块,然后继续

但是这段代码,也会在打印行后发生错误

因为它在try-catch之外,这就是异常处理的优势

异常处理可防止程序因运行时错误而异常终止。事情就是这样

另见

因此,您也将在输出中获得这一行。

在输入
catch
块后,流将继续,因此要执行的下一行是底部打印

如果要从
捕获中终止,请执行以下操作:

try {
    int a = sn.nextInt();
} catch (InputMismatchException ex) {
    System.out.println("error please enter integer value");
    return; // program will end
}

如果您希望终止,则需要重新引发异常,例如:

System.out.println("enter value integer ");
Scanner sn = new Scanner(System.in);
try {
    int a = sn.nextInt();
} catch (InputMismatchException ex) {
    System.out.println("error please enter integer value");

    throw new RuntimeException(ex);
}

System.out.println("not terminating"); // this is out side the try-catch
这样就不会打印最后一个系统输出,而是得到一个stacktrace

System.out.println("enter value integer ");
Scanner sn = new Scanner(System.in);
try {
    int a = sn.nextInt();
} catch (InputMismatchException ex) {
    System.out.println("error please enter integer value");

    throw new RuntimeException(ex);
}

System.out.println("not terminating"); // this is out side the try-catch