簡體   English   中英

關於試捕

[英]Regarding try-catch

我目前正在學習Java入門課程,這是關於try-catch方法的。 當我鍵入此內容時, System.out.println語句會不斷重復。 這是我的代碼:

public static double exp(double b, int c) {
    if (c == 0) {
        return 1;
    }

    // c > 0
    if (c % 2 == 0) {
        return exp(b*b, c / 2);
    }
    if (c<0){
        try{
        throw new ArithmeticException();
        }
        catch (ArithmeticException e) {
            System.out.println("yadonegoofed");
        }
    }

    // c is odd and > 0
    return b * exp(b, c-1);
}
if (c<0){
    try{
    throw new ArithmeticException();
    }
    catch (ArithmeticException e) {
        System.out.println("yadonegoofed");
    }
}

// c is odd and > 0
return b * exp(b, c-1);

您的注釋c is odd and > 0是不正確的-您從未真正終止過帶有異常的函數。 您把它扔了,立即抓住了它,然后繼續執行遞歸函數。 最終,當您繞回時 ,它將再次為正數,並且不會發生錯誤。 (大約有二十億次迭代-不要等待。)

我不會在這里使用異常-您只需要終止遞歸即可。 我會先檢查是否有負輸入, 然后再檢查0 ,然后在其中拋出異常,並在調用方中捕獲異常

用偽代碼:

exp(double b, int c) {
    if (c < 0)
        throw new Exception("C cannot be negative");
    } else if (c % 2 == 0) {
        return exp(b*b, c / 2);
    } else {
        /* and so forth */
    }
}

在創建自己的自定義異常時,您忘記了一個非常重要的部分。 您忘了告訴方法它將拋出這樣的方法。 您的第一行代碼應如下所示:

public static double exp(double b, int c) throws ArithmeticException {

請注意,我自己對此進行了測試,它只會在您的輸出中拋出一次異常。

例如,如果c = -1 in,則第一個if失敗,第二個if失敗,第三個if拋出異常,然后輸出錯誤,但是事情進展了,因為您已處理了問題。 因此它調用exp(b,-2)。 反過來,它在返回中調用exp(b,-3),依此類推。 將C的值添加到您的println中進行驗證。

好吧,最后,您將return b * exp(b, c-1); 這將再次調用exp ,它將再次調用它。
因此,該函數將繼續重復執行, System.out.println也將重復執行。

您的BASE案例非常特定...在代碼保證中c等於0的情況是什么? 當前,這是退出遞歸調用的唯一方法。 正如@Jay所說,您總是減去1導致拋出的異常,但是c在那時已經低於0了,所以它不等於0。更改您的第一個if語句以捕獲值<= 0,就可以了。

if( c <= 0 )
     return 1;

暫無
暫無

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

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