簡體   English   中英

為什么會出現編譯錯誤? 使用 try and catch

[英]Why do I get compile error? using try and catch

public static void main(String[] args) {
        // TODO Auto-generated method stub

        int x = 0, y = 10;
        try {
            y /=x;
        }
        System.out.print(" / by 0");
        catch(exception e) {
            System.out.print("error");
        }
}

使用 try and catch,我在上面構建了代碼,output 是編譯錯誤。 我預期的 output 是“錯誤”,因為數字除以零會產生 ArithmeticException。 為什么會出現上面的編譯錯誤?

您不能將trycatch塊分開。 這給了你編譯錯誤。 正確的代碼是:

public static void main(String[] args) {
    int x = 0, y = 10;
    try {
        y /= x;
    } catch (Exception e) {
        System.out.print(" / by 0");
        System.out.print("error");
    }
}

此外,您有Exception小寫,這會導致另一個問題。

catch 塊應該緊跟在 try 塊之后。 將打印行語句放在 catch 塊中。 此外,異常是 Java 的 class,不是異常。

因此,將 catch 關鍵字放在 try 塊 (}) 結束后立即,或放在下一行。

暫無
暫無

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

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