views:

53

answers:

4

I would like to ignore a specific Type of exception in a group of statements; without having to put empty Try..Catches around them.

try{ o1.Update(); } catch (Exceptions.NoChangeMade ex) {}
try{ o2.Update(); } catch (Exceptions.NoChangeMade ex) {}
try{ o3.Update(); } catch (Exceptions.NoChangeMade ex) {}

I would like either a On Error Resume type way, or a Continue way within the catch

+3  A: 

If you want them all to update, you don't really have a choice without wrapping the exception.

You could do something like:

var list = List<objects_to_update> ();

 list.Add(o1);
 list.Add(o2);
 etc.    

list.ForEach(x=>
  try{list.Update()}
  catch{}
 );

You'll still have to wrap them in an exception, but at least this way you're only writing it once.

Kevin
The only other alternative is handling the exception in `Update`.
Jeff Sternal
@Jeff, that is true too. I was going on the assumption that he couldn't alter the update statement.
Kevin
I agree with that assumption ... if the Exception is useless enough to be safely ignored, then if the OP has control over Update he should just not have it throw the exception at all.
Joren
A: 

If o1/o2/o3 are all the same class then put 1 try catch in the .Update() method to catch the specific exception that you are looking for. Or better yet, change the code so that it does not throw the exception at all.

Greg Bahrey
+3  A: 

Here's a simple way:

ExecuteIgnore(o1.Update);
ExecuteIgnore(o2.Update);
ExecuteIgnore(o3.Update);
...
private static void ExecuteIgnore(Action action)
{
    try { action(); }
    catch(Exceptions.NoChangeMade) { }
}

You can make it even more generic (if a bit longer) like this:

ExecuteIgnore<Exceptions.NoChangeMade>(o1.Update);
ExecuteIgnore<Exceptions.NoChangeMade>(o2.Update);
ExecuteIgnore<Exceptions.NoChangeMade>(o3.Update);
...
public static void ExecuteIgnore<T>(Action action) where T : Exception
{
    try { action(); }
    catch(T) { }
}
Joseph Sturtevant
+1  A: 

Are these o1, o2, o3 objects related? Could you put them in a collection or an array?

If you do this, you could modify your code to use a loop to update the items and then you could have the empty catch block effectively pass control on to the next iteration of the loop.

Some pseudocode to illustrate:

foreach(DataTypeOfO o in CollectionOfOs)
{
    try
    {
          o.Update(); 
    }
    catch(Exceptions.NoChangeMade ex)     
    { }
}
Paddyslacker