【发布时间】:2018-05-23 17:11:36
【问题描述】:
我已经读到可以创建一个构造函数来检查输入是否正确,我尝试使用 IllegalArgumentException 来执行此操作。只要我不创建对象,我的代码就可以正常工作,无论输入是否正确,编译器都会出错。这是我的代码:
public class Knoten{
private String typ;
public Knoten(String typ) throws Exception{
try{
if (typ.equals ("BASE")||typ.equals ("WORD")||typ.equals ("ROOT")||typ.equals ("AFFIX")){
this.typ=typ;
}}catch(IllegalArgumentException ex){
System.out.println ("invalid typ");
}}
public String getTyp(){
return typ;
}
public String toString(){
return "typ: "+getTyp();
}
public static void main (String args[]){
Knoten Knot1= new Knoten("haha");//throws error
Knoten Knot2= new Knoten("BASE");//throws error
}}
我也尝试过这样做,得到了相同的结果:
public class Knoten{
private String typ;
public Knoten(String typ) throws Exception{
if (typ.equals ("BASE")||typ.equals ("WORD")||typ.equals ("ROOT")||typ.equals ("AFFIX")){
this.type=type;
}else{
throw new IllegalArgumentException("invalid type");
}
}
public String getTyp(){
return typ;
}
public String toString(){
return "typ: "+getTyp();
}
public static void main (String args[]){
Knoten Knot1= new Knoten("haha");//throws error
Knoten Knot2= new Knoten("BASE");//throws error
}
}
所以我的问题是我是否必须在每次创建该类的对象时处理异常,或者是否有更好的方法。
【问题讨论】:
-
type是什么?你的变量名是typ。试试typ.equals("BASE") -
是的,对不起,我编辑了它,这不是问题。
-
第一种方法行不通。你没有抛出异常。您是否尝试过调试第二个场景?
标签: java validation exception exception-handling