即使不符合条件,也要保持抛出异常

Gle*_*imo 2 java exception throw

这可能是一个非常棒的问题,但我想我会抓住机会.

所以基本上我必须做一个任务,它如下:

我必须创建一个构造函数,但变量"naam"不能为null或为空(""),变量"geboortedatum"不能在将来也不能与今天和最后一个变量相同" boeken"与变量"naam"具有相同的要求(因为它不能为null也不能为"").

所以这就是我的构造函数的样子,我只能编辑这部分,因为另一部分是由我们的老师给出的,不能编辑.

        if (this.naam == null || this.naam.equals("")) {
        throw new IllegalArgumentException("Fill in name");
    } else {
        this.naam = naam;
    }
    Date vandaag = new Date();
    if (this.geboorteDatum >= vandaag.getTime()) {
        throw new IllegalArgumentException("Date must be in the past");
    } else {
        this.geboorteDatum = geboortedatum;
    }
    if (this.boeken == null || Arrays.toString(boeken).equals("")) {
        throw new IllegalArgumentException("Can't be empty");
    } else {
        this.boeken = boeken;
    }  
Run Code Online (Sandbox Code Playgroud)

它不断抛出我的第一个例外,我无法弄清楚为什么.这可能是一个非常愚蠢的问题,但我似乎无法找出原因.

任何帮助将非常感谢,提前感谢

T.J*_*der 8

您正在测试this.naam,这是该类的实例数据成员.如果这是在你所说的构造函数中,那么除非你有一个初始化器,否则它可能就是null.

你可能打算测试naam一下构造函数的参数:

if (naam == null || naam.equals("")) {
//  ^---------------^------------------ no `this.` here
    throw new IllegalArgumentException("Fill in name");
} else {
    this.naam = naam;
}
Run Code Online (Sandbox Code Playgroud)

同样的geboortedatumboeken.