Say*_*iss 2 java constructor exception
我实现了一个类:
public class TableInfoGroup {
Vector<TableInfo> tableInfoVector;
public TableInfoGroup(Vector<String> tableNameVector, Vector<String> tableTagIdVector)
{
if (tableNameVector.size() != tableTagIdVector.size())
return;//I think it's not proper to do this
tableInfoVector = new Vector<TableInfo>();
for(int i = 0; i < tableNameVector.size(); i++)
tableInfoVector.add(new TableInfo(tableNameVector.get(i), tableTagIdVector.get(i)));
}
}
Run Code Online (Sandbox Code Playgroud)
怎么做那优雅?抛出异常?谢谢.
就个人而言,我会让方法抛出IllegalArgumentException:
抛出以指示方法已被传递非法或不适当的参数.
例如:
if (tableNameVector.size() != tableTagIdVector.size())
throw new IllegalArgumentException("tableNameVector and tableTagIdVector " +
"must have the same size");
Run Code Online (Sandbox Code Playgroud)
即使IllegalAgumentException是未经检查的异常,我仍然会将其作为文档添加到方法的throws子句中.
使构造函数抛出异常会阻止构造对象,我认为这是正确的操作过程.