簡體   English   中英

從 Java 中的 try catch 塊獲取變量的問題

[英]Problem with getting variable from try catch blocks in Java

我的程序有一個奇怪的問題。 我寫了以下代碼:

class Divide{

    int a, b;

        int divide(int a, int b) {

            try {

             if (b > 1)
                    throw new ArithmeticException("Generating exception");}
             catch (ArithmeticException e) {
                System.out.println("Caught exception 1st time" + e);

             throw e;

            }
        int c = a / b;


        return c; 
    } 
}

之后我想做異常處理並通過以下方式從中獲取變量:

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    Divide d = new Divide();

    int result = 0;

                    try
                    {
                        result = d.divide(12, 2);

                    } catch (ArithmeticException e)
                    {
                        System.out.println("2 raz");
                    }

                    System.out.println(result); ///getting 0 insted of 6!

    }

}

而且我在 try-catch 塊之前仍然變得可變。 如何在使用 divade 方法后進行此類異常處理並獲取帶值的變量。

因為每當 b 大於 0 時就會拋出異常,所以當你以 2 的值運行它時會拋出異常。因此,結果永遠不會更新,並且在程序結束時顯示 0。

要獲得正確的輸出,您需要將divide 方法中的if 語句更改為在b 大於1 時不拋出異常。

catch with throw e; 你重新拋出一個已經捕獲的錯誤。
這就是為什么這

int c = a / b;

不被執行。
如果你刪除

throw e;

結果你會得到 6。

暫無
暫無

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

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