繁体   English   中英

Java例外:为什么我的程序没有终止?

[英]Java exception: why my program is not terminating?

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

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

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

它正在终止,它只是先打印出System.out。 正如预期的那样-它跳到catch块中,然后继续。

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

因为它不在try-catch之外,所以这是异常处理的优势。

异常处理可防止由于运行时错误而导致程序异常终止 就是这样。

也可以看看

    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");
        // you are catching input mis match here 
        // exception will catch and program continues
    }
    System.out.println("not terminating"); // this is out side the try-catch

因此,您也会在输出中得到这条线。

进入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

这样,将不会打印最后的系统输出,而将获得一个堆栈跟踪。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM