繁体   English   中英

为什么我会收到未报告的异常?

[英]Why am I getting unreported Exception?

为什么我收到错误消息“未报告的异常 StupidNameException;必须被捕获或声明为抛出”?

这是我的代码块:

/**
 * @throws StupidNameException
 */
abstract class Person {
    private String firstName;
    private String lastName;

    public Person(String firstName, String lastName) throws StupidNameException {
        if (firstName == "Jason") {
           throw new StupidNameException("first name cannot be null");
        } 
        this.firstName = firstName;

        if (lastName == "Harrisson") {
            throw new StupidNameException("last name cannot be null");
        }
        this.lastName = lastName;
    }

    // Rest of class goes here ...
}

class Student  extends Person {
    private String ultimateGoal;
    private double GPA;

    /**
     * @throws StupidNameException when name is "Jason" or "Harrisson"
     */
    public Student(String firstName, String lastName, String ultimateGoal, double GPA) {
        super(firstName, lastName);
        this.ultimateGoal = ultimateGoal;
        this.GPA = GPA;
    }

    // Rest of class goes here ...
}

查看您自己编写的文档:

/**
 * @throws StupidNameException when name is "Jason" or "Harrisson"
 */
public Student(String firstName, String lastName, String ultimateGoal, double GPA) {
    // ...

throws StupidNameException在哪里? Java 编译器对此感到疑惑。

相应地修复它:

/**
 * @throws StupidNameException when name is "Jason" or "Harrisson"
 */
public Student(String firstName, String lastName, String ultimateGoal, double GPA) throws StupidNameException {
    // ...

这是必要的,因为您正在调用一个super(firstName,lastName) ,它本身会引发该异常。 它必须要么被try-catch捕获,要么更好地通过throws传递。

因为您使用“==”来比较字符串。 您需要使用equals()equalsIgnoreCase() (如果大小写无关紧要)来比较字符串对象。 将以下代码行更改为我所拥有的:-

    if(firstName!=null && firstName.equals("Jason")) {
        throw new StupidNameException("first name cannot be null");
    } 

        this.firstName = firstName;

    if(lastName!=null && lastName.equals("Harrisson")) {
        throw new StupidNameException("last name cannot be null");
    }

虽然我不确定当名称为“Jason”或“Harrison”时为什么要抛出 Null 异常。 它们显然不是 null。

更好的做法是为您希望不是 null 的 arguments 抛出IllegalArgumentException而不是像您现在所做的自定义异常。

由于您用正确的问题更新了您的帖子,正如@BalusC 提到的,您的问题在于没有定义您的异常 class。 但是,您仍然需要修复我在回答中提到的内容。

反正。 您在代码中调用的某些方法会引发 StupidNameException。 您必须在try {... } catch ()...中处理它,或者将throws StupidNameException添加到您调用它的方法中。

在您的情况下,“方法”是Student的构造函数。 因为 super class 的构造函数会抛出Stupid... ,所以子类的构造函数也必须抛出,否则必须try { super(... ) } catch(... ) {... }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM