如果输入的客户名称为 null,则应该抛出异常,但我的代码不起作用。
public class CustomerAccount {
private String name;
public CustomerAccount(String name) throws IllegalArgumentException {
this.setName(name);
}
public String getName() {
return name;
}
public void setName(String name) throws IllegalArgumentException {
try {
this.name = name;
}
catch (IllegalArgumentException illegal) {
if (name == "" || name == null) {
System.err.println("please do not enter the empty string" + illegal);
}
}
}
public String toString() {
return "Name: " + this.getName();
}
public static void main(String[] args) {
CustomerAccount c1 = new CustomerAccount("random name");
c1.setName(null);
System.out.println(c1);
}
}
最佳答案
如果名称为 null 或为空(该方法中没有 try/catch),setName 应该简单地抛出 IllegalArgumentException。
public void setName(String name) throws IllegalArgumentException {
if ("".equals(name) || name == null) {
throw new IllegalArgumentException("Name should not be null or empty");
}
this.name=name;
}
关于java - 为什么我的异常(exception)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32713526/