簡體   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