kal
kal

Reputation: 29361

Exception handling continue on error and then rethrow

     //Assume list1 and list2 are populated with states as 2
    foo (List<Class1> list1, List <Class1> list2) {

         boolean error = false;
          try {
             operate on list1
         } catch (Exception e) {
              error = true;
             //Modify list1 objects to state 1
        }

          try {
             operate on list2
         } catch (Exception e) {
              error = true;
             //Modify list2 objects to state 1
         }

        //What are the problems and what is the best practice for this
         if (error)
             throw new Exception(…);  //How should i really rethrow the exception

    }

Upvotes: 0

Views: 215

Answers (2)

Ryan Stewart
Ryan Stewart

Reputation: 128809

The main improvement I'd make is to store all exceptions that occur and make them available somehow, somewhere. Otherwise, it seems fine.

To the skeptical, it's not really abnormal to want to complete some work even when an exception happens. Batch processing is a pretty typical case.

Upvotes: 2

Hot Licks
Hot Licks

Reputation: 47729

Nothing technically wrong with it, other than getting the throws clause correct, etc. You could even save one of the caught exceptions and re-throw it.

Not clear why you'd want to do this, but I've done weirder.

Upvotes: 0

Related Questions