简体   繁体   English

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

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

When I run my simple code and enter char instead of integer value which was supposed to be Entered. 当我运行我的简单代码并输入char而不是应该输入的整数值时。 Program, listed below is supposed to be terminated after printing "error please Enter integer value" . 打印“错误,请输入整数值”后,下面列出的程序应终止。

But this code, also printing the line after Occurrence of error 但是这段代码,也会在出现错误后打印行

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

It is terminating, it just prints out the System.out first. 它正在终止,它只是先打印出System.out。 This is as expected - it jumps into the catch block, and then continues. 正如预期的那样-它跳到catch块中,然后继续。

But this code, also printing the line after Occurrence of error 但是这段代码,也会在出现错误后打印行

Because it is out side of try-catch, that is the advantage of exception handling. 因为它不在try-catch之外,所以这是异常处理的优势。

Exception handling prevents the abnormal termination of program due to run time error. 异常处理可防止由于运行时错误而导致程序异常终止 And that is what happened. 就是这样。

See also 也可以看看

    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

So you will get this line in your out put too. 因此,您也会在输出中得到这条线。

After entering the catch block, flow continues on, so the next line to execute is the bottom print. 进入catch块后,流程继续进行,因此要执行的下一行是底部打印。

If you want to terminate from within the catch : 如果要从catch终止:

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

If you want it to be terminated you need to re-throw the exception eg: 如果要终止它,则需要重新引发异常,例如:

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

That way the last system output would not be printed and you would get a stacktrace instead. 这样,将不会打印最后的系统输出,而将获得一个堆栈跟踪。

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

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