簡體   English   中英

try / catch塊中的多個語句 - Java

[英]multiple statements in try/catch block - Java

我有點不確定這是否:

    try{
        worldHeight = Integer.parseInt(JOptionPane.showInputDialog("How many cells high will the world be?: "));
        }
        catch (NumberFormatException e){
            JOptionPane.showMessageDialog(null, "You have not entered a valid number");
        }

    try{
        worldWidth = Integer.parseInt(JOptionPane.showInputDialog("How many cells wide will the world be?: "));
        }
        catch (NumberFormatException e){
            JOptionPane.showMessageDialog(null, "You have not entered a valid number");
        }

會做同樣的事情:

    try{
        worldHeight = Integer.parseInt(JOptionPane.showInputDialog("How many cells high will the world be?: "));
        worldWidth = Integer.parseInt(JOptionPane.showInputDialog("How many cells wide will the world be?: "));
        }
        catch (NumberFormatException e){
            JOptionPane.showMessageDialog(null, "You have not entered a valid number");
        }

基本上希望用戶輸入一個數字,如果不是數字異常被拋出並且用戶被重新詢問一個數字?

謝謝

在您的第一個示例中,使用兩個單獨的try...catch塊,似乎拋出異常時,您只是顯示一個對話框,而不是停止控制流。

因此,如果在第一次try...catch有異常,則控制將繼續到第二次try...catch並且將要求用戶輸入第二個數字,而不管她沒有進入第一個數字正確。

在第二個示例中,如果第一個try...catch存在異常,則不會向用戶顯示第二個問題,因為控件不會在try塊內繼續,而是在catch塊結束后繼續。

是的,這將(幾乎)相同。 在try catch塊中,它只會在發生錯誤的位置停止執行。 如果它在第一行拋出錯誤,則第二行永遠不會執行第二行。 這是唯一的區別,在第一個選項中,無論第一行(輸入)是否拋出錯誤,都將執行第二行(輸入)。

您也可以嘗試以下代碼

{
    int arr[]=new int[5];
    try
    {

        try
        {
            System.out.println("Divide 1");
            int b=23/0;
        }
        catch(ArithmeticException e)
        {
            System.out.println(e);
        }
        try
        {
            arr[7]=10;
            int c=22/0;
            System.out.println("Divide 2 : "+c);
        }
        catch(ArithmeticException e)
        {
            System.out.println("Err:Divide by 0");
        }
        catch(ArrayIndexOutOfBoundsException e) 
    //ignored 
        {
            System.out.println("Err:Array out of bound");
        }
    }
    catch(Exception e)
    {
        System.out.println("Handled");
    }
}

有關更多詳細信息,請訪問: 帶有示例的java中的多個try-catch

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM