Type checking by InvalidCastException:
Common uses:
- Checking the type of an object in a collection when the developer does not know about the "is" operator or its equivalents.
Selection selItems = UtilServices.GetInstance().GetSelectedItems();
if (selItems != null)
{
try
{
foreach (object item in selItems)
{
// Cast to a Foo Item.
FooItem fooItem = (FooItem)item;
}
ProcessSuccess();
}
catch (System.Exception ex)
{
// If an exception is thrown, the items are not FooItems
Logger.Error("Exception: " + ex.Message);
ProcessFailure();
}
}
Null checking by Exception handler:
Common uses:
- Not being bothered by the hassle of all those "if" statements.
try
{
foo = bar.GetSomeData();
thing = foo.ThingValue;
}
catch
{
foo = bar.GetOtherData();
thing = foo.ThingValue;
}
1 comment:
Those are pretty rough samples and I've see my fair share of abusive use of exception catching.
LINQ makes it really easy to check if all the items in a collection are of a certain type. Here's how to do it in one line:
bool areAllItmesFooItem = selItems.All(i => i is FooItem);
Post a Comment