If you need to throw an exception when the cast is invalid, why are you bothering to catch the normal InvalidCastException
? Just cast it with no extra code:
WizardStep parentWizardStep = (WizardStep) Parent;
You're currently replacing an exception which conveys its meaning in its type (InvalidCastException
- at least, so you hope) with bare Exception
- why do you want to lose information?
The above is certainly what I always do if it's a bug for the relevant value to not be of the correct type. Otherwise, use the as
operator and a null check:
WizardStep parentWizardStep = Parent as WizardStep;
if (parentWizardStep == null)
{
// It wasn't a WizardStep. Handle appropriately
}
else
{
// Use the WizardStep however you want
}
But either way, it's horrible to do something that you know might throw an exception, and where it's easy to test to avoid the exception, but choosing to catch it instead. The efficiency will be poor, but more importantly it's just an inappropriate use of exceptions. Aside from anything else, you're currently catching all exceptions... what if fetching this.Parent
throws some completely different kind of exception? It may have nothing to do with casting. Only catch specific exceptions unless you're trying to implement some top-level "catch-all" handler (e.g. to abort server requests).