请查看以下代码:
public void editProduct(String articleNumber, ...) {
product.setArticleNumber(articleNumber);
product.setDescription(description);
product.setLendable(lendable);
product.setName(name);
product.setPrice(price);
product.setPlace(place);
}
所有setter都可以使用自定义消息抛出ProductException。
但我想抓住所有例外情况。如果有例外,我想向GUI发送所有错误的列表
我该怎么做,或者我需要用Try Catch包围每一行吗?
答案 0 :(得分:1)
哟可以尝试以下代码。如果合适的话
public void editProduct(String articleNumber, ...) {
int count=1;
Vector<String> v=new Vector<String>();
while(count<=6)
{
try{
switch(count)
{
case 1:product.setArticleNumber(articleNumber);break;//assume it will throw ArticalException
case 2:product.setDescription(description);break; //DescriptionException
case 3:product.setLendable(lendable);break; //LendableException
case 4:product.setName(name);break; //NameException
case 5:product.setPrice(price);break; //PriceException
case 6:product.setPlace(place);break; //PlaceException
}
count++;
}catch(Exception e)
{
v.add(e.getMessage);
count++;
/*
*suppose there is some exception like ArticalException,PriceException
*then it will store in vector and your program running continue
*and at last you have the list of all exceptions that are occured in program
*now you will take desired action what you want to do
**/
}
}
}
答案 1 :(得分:0)
如果你需要列表中的所有异常,那么你必须通过try catch包围每一行并在列表中添加异常,并在最后一次检查中列表的大小大于0然后将该列表作为异常返回。 / p>
List<CustomException> exceptionList = new ArrayList<CustomException>();
public void editProduct(String articleNumber, ...)
{
try{
product.setArticleNumber(articleNumber);
}catch(CustomException exception)
{
exceptionList.add(exception);
}
try{
product.setDescription(description);
}catch(CustomException exception)
{
exceptionList.add(exception);
}
try{
product.setLendable(lendable);
}catch(CustomException exception)
{
exceptionList.add(exception);
}
try{
product.setName(name);
}catch(CustomException exception)
{
exceptionList.add(exception);
}
try{
product.setPrice(price);
}catch(CustomException exception)
{
exceptionList.add(exception);
}
try{
product.setPlace(place);
}catch(CustomException exception)
{
exceptionList.add(exception);
}
}
答案 2 :(得分:0)
如果你真的想做这样的事情,可以将属性设置委托给一个方法,该方法可以捕获将setter作为lambda运行,然后捕获可能的异常,或将其添加到列表中:
class C {
@FunctionalInterface
private static interface TaskMayThrow {
void run() throws CustomException;
}
private static boolean runTask(TaskMayThrow task, List<CustomException> errList) {
try {
task.run();
return true;
} catch(CustomException e) {
errList.add(e);
return false;
}
}
List<CustomException> exceptionList = new ArrayList<CustomException>();
public void editProduct(String articleNumber, ...)
{
runTask(() -> product.setArticleNumber(articleNumber), exceptionList);
runTask(() -> product.setDescription(description), exceptionList);
// The same for all other setters
// Do whatever you want with the error list
}