簡體   English   中英

處理 Java 自定義異常

[英]Handling Java custom exceptions

更新:

我已經修復了語法錯誤並刪除了異常處理,並且我得到了完全相同的錯誤消息(當然是不同的行號):

class Point {
    public Point (int x, int y) {
        this.x = x;
        this.y = y;
    }

    public void displayPointPosition() {
        System.out.println("Position: " + x + " " + y);
    }
    private int x, y;
}

public class Exinfo2 {
    public static void main(String args[]) {
        Point a = new Point(1, 4);
        a.displayPointPosition();
        a = new Point(-3, 5);
        a.displayPointPosition();
    }
}

這真的一定是初學者的錯誤,我的代碼編輯器(Visual Studio Code)沒有突出顯示任何錯誤......

==============

我正在學習 Java,現在正在嘗試處理自定義異常,但沒有成功。 我在編譯代碼時遇到各種錯誤消息,我什至從我從書中復制的示例中遇到了問題,所以似乎除了代碼之外可能還有其他東西......

這是我正在嘗試制作的示例,我收到了編譯器消息:

"Exception in thread "main" java.lang.Error: Unresolved compilation problem: 

        at Exinfo2.main(Point.java:23)".

這是代碼:

class Point {
    public Point (int x, int y) throws ErrConst {
        if ( (x < 0) || (y < 0) ) {
          throw new ErrConst ("Constructor error:" + x + " " + y);
        }
        this.x = x;
        this.y = y;
    }

    public void displayPointPosition() {
        System.out.println("Position: " + x + " " + y);
    }
    private int x, y;
}

class ErrConst extends Exception {
    ErrConst(String mes) {
        super(mes);
    }
}

public class Exinfo2 {
    public static void main(String args[]) {
        try {
            Point a = new Point(1, 4);
            a.displayPointPosition();
            a = new Point(-3, 5);
            a.displayPointPosition();
        }
        catch (ErrConst e) {
            System.out.println(e.getMessage());
            System.exit(-1);
        }
    }
}

我確定這是非常基本的,但這對我來說很頭疼,所以我希望一位善良的編碼員可以花幾分鍾來幫助我...... :-)

提前致謝! :-)

當我嘗試運行它時,您的代碼運行良好。

但是,根據您發布的異常,您似乎已將該文件另存為Point.java 您在同一個文件中有多個類,但您的公共類稱為Exinfo2 在 Java 中,文件名和公共類的名稱必須相同,所以這可能是問題所在。

嘗試將文件Exinfo2.javaExinfo2.java


但是,您從編譯器獲得的錯誤消息很奇怪。 通常,您會收到錯誤消息“類 Exinfo2 是公共的,應在名為 Exinfo2.java 的文件中聲明”。 看起來你得到的錯誤來自 Eclipse 編譯器,所以也許 Visual Studio Code 插件正在使用該編譯器而不是常規編譯器。 嘗試從命令行像這樣編譯它:

javac Exinfo2.java
java Exinfo2

我認為在您的 Point 類中..方法displayPointPosition .. PrintStream 未找到您的消息.. 你可以嘗試更改它..為此: System.out.println("Position: " + x + " " + y) ;

問候!

暫無
暫無

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

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