我正在尝试编写一个在用户为实例变量输入数据时进行数据验证的类。这个类中没有主要方法,只有构造函数。用户输入在测试工具中完成。我的问题是我是否像在此处所做的那样在 set 方法中进行异常处理?还是我应该尝试在其中一个构造函数中捕获?
public class Customer
{
private String fName;
private String lName;
private String custTIN;
private int custNbr;
private int custHonor;
public Customer(String first, String last, String tin, int cust, int honor)
{
setFName(first);
setLName(last);
setCustTIN(tin);
setCustNbr(cust);
setCustHonor(honor);
}
public Customer(String first, String last, int cust, String tin)
{
setFName(first);
setLName(last);
setCustTIN(tin);
setCustNbr(cust);
}
/**************************************************************************************************************
* Set & Get Methods
**************************************************************************************************************/
public void setFName(String first) throws InvalidCustomerException
{
if(first == "null")
{
throw new InvalidCustomerException("You did not enter any data");
}
else
{
fName = first;
}
}
public void setLName(String last)
{
lName = last;
}
public void setCustTIN(String tin)
{
custTIN = tin;
}
public void setCustNbr(int cust)
{
custNbr = cust;
}
public void setCustHonor(int honor)
{
custHonor = honor;
}
public String getFName()
{
return fName;
}
public String getLName()
{
return lName;
}
public String getCustTIN()
{
return custTIN;
}
public int getCustNbr()
{
return custNbr;
}
public int getCustHonor()
{
return custHonor;
}
/****************************************************************************************************************
* toString Methods
****************************************************************************************************************/
//public String createSalutaion()
{
}//end createSalutation()
public String toString()
{
return String.format ("%d %s %s, Customer number %d, with Tax Id: %s", getCustHonor(), getFName(), getLName(), getCustNbr(), getCustTIN());
}//end toString()
}
这是我的异常类.....
/**
* Auto Generated Java Class.
*/
public class InvalidCustomerException extends Exception
{
private String inputValue = "null";
public InvalidCustomerException(String message)
{
super(message);
}
public InvalidCustomerException(String message, Throwable cause)
{
super(message,
cause);
}
public InvalidCustomerException(String message, String inputValue)
{
}
public InvalidCustomerException(String message, String inputValue, Throwable cause)
{
}
} // end of invalid customer exception
最佳答案
就个人而言,我喜欢确保错误的数据从一开始就不会被传递,在收集传递给构造函数的数据时,会 try catch 和抛出错误(通常是 IllegalArgumentException,因为它毕竟是这样)。
但是要回答您的问题,最好尽快拦截错误,以避免在依赖输入数据正确的后续函数中出现未定义的行为或垃圾中的垃圾,这就是这里的事情,能力重新提交搞砸的输入。但是由于您不直接设置实例变量,因此您的设置工作得很好,只要您可以从用户那里获取数据来纠正任何搞砸的东西。
关于java - 在哪里抛出异常句柄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33381198/