繁体   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