I would like to ignore a specific Type of exception in a group of statements; without having to put empty Try..Catch
es开发者_如何学JAVA 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
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) { }
}
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.
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)
{ }
}
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.
精彩评论