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

时间:2011-08-10 23:54:15

标签: 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 ...
}

3 个答案:

答案 0 :(得分:5)

查看您自己编写的文档:

/**
 * @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传递。

答案 1 :(得分:2)

因为您使用“==”来比较字符串。您需要使用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的参数而不是像现在这样的自定义异常,抛出IllegalArgumentException是一种更好的做法。

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

答案 2 :(得分:2)

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

在您的情况下,“method”是Student的构造函数。 因为超类的构造函数抛出Stupid...,所以子类构造函数也必须抛出,或者你必须执行try { super( ... ) } catch( ... ) { ... }