我刚开始学习java.我正在尝试学习异常处理的工作原理,所以我编写了一个小程序:
public class Car {
protected String type;
protected String[] colors;
protected boolean isAvaiable;
public Car(String type, Collection<String> colors, boolean isAvaiable) throws NoColorException {
if (colors == null || colors.isEmpty()) {
throw new NoColorException("No colours!");
} else {
this.type = type;
this.colors = (String[]) colors.toArray();
this.isAvaiable = isAvaiable;
}
}
public static void main(String[] args) {
try {
Car n = new Car("asd", new ArrayList(), true);
} catch (NoColorException ex) {
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的Exception类:
public class NoColorException extends Exception {
public NoColorException(String string) {
super(string);
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试创建对象但是它运行时,上面的代码应该抛出一个异常.
为什么会这样?
任何帮助是极大的赞赏.
您的代码抛出一个异常,您在空的catch块中捕获该异常:
catch (NoColorException ex) {
}
Run Code Online (Sandbox Code Playgroud)