1

Look at the following code:

public void editProduct(String articleNumber, ...) {
 product.setArticleNumber(articleNumber);
 product.setDescription(description);
 product.setLendable(lendable);
 product.setName(name);
 product.setPrice(price);
 product.setPlace(place);
}


All of the setters can throw a ProductException with a custom message. But I want to catch all the exceptions. If there are exceptions, I want to send a list to the GUI of all the errors.

How can I do this, or do I need to surround every line with a Try Catch?

Demian
  • 390
  • 2
  • 14
  • If an exception occurs, why do you want to carry on trying to change the product? If an exception occurs, it indicates a problem; and the `product` should be left in the state it was before you started trying to edit it (*Effective Java* refers to this as ["failure atomicity"](http://stackoverflow.com/questions/29842845/what-is-failure-atomicity-used-by-j-bloch-and-how-its-beneficial-in-terms-of-i)). – Andy Turner Apr 30 '16 at 11:05
  • Hi, I want to show the user the different errors: ' - There is no description, - There is no price - ... ' – Demian Apr 30 '16 at 11:08
  • What is an exception for you here?The product to be null?Some of method parameters to be null?These methods are simple setters?How the exception may occur here ... – GOXR3PLUS Apr 30 '16 at 11:17
  • Hello, exceptions like null, whitespace or empty value, logic (name need to be unique), ... – Demian Apr 30 '16 at 11:21

3 Answers3

1

Yo can try the following code. if it is suitable

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 
             **/
        }
    }

}
Sharad Gautam
  • 91
  • 5
  • 11
  • Hi, I like you solution! I don't know of it's the best practice A little thing, if a setter fails, the count will still be the same. So your have an infinite loop. Maybe you can increment before the switch, or in the finally group? – Demian Apr 30 '16 at 11:52
  • look at my code.. there is a count++ statement.there is count++ statement after switch and in catch block – Sharad Gautam Apr 30 '16 at 12:05
  • Yea ... but `for (count = 1; count <= 6; count++) ` does the same thing, and it is much more readable. Also, you should catch `ProductException`. Catching `Exception` is a bad idea, 'cos it will cause unexpected exceptions to be reported to the user as validation errors. – Stephen C Apr 30 '16 at 13:33
  • Yes .nice. but i have just give you the idea to solve the problem.you can modify it according to your requirements – Sharad Gautam Apr 30 '16 at 13:41
0

if you need all the exceptions in list then you have to surround each line by try catch and add the exception in a list and in the last check the size of the list is greater than 0 then return that list as exception.

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);
      }
}
  • Thank you, but is there not a better solution for this? – Demian Apr 30 '16 at 11:17
  • rather than throwing exception from setter method you can just add a validate method for handling your all setter check and perform all your operation there for all the fields validations.that would be batter approach. – Lakhan singh Apr 30 '16 at 11:28
  • Hi, that's a possibility. But I want to keep all the "domain" code in the domainclass. – Demian Apr 30 '16 at 11:42
0

If you really want to do such a thing, you could delegate the property setting to a method that would catch run the setter as a lambda, then catch the possible exception, or add it to a list:

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
     }
Javier Martín
  • 2,537
  • 10
  • 15