为什么我得到未报告的例外?

1 java 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 ...
}
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 5

查看您自己编写的文档:

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

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

相应修复:

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

这是必要的,因为你正在调用一个super(firstName,lastName)它自己抛出异常.它要么被捕获try-catch,要么更好地被传递throws.