Getting type of exception

3 views
Skip to first unread message

rbr

unread,
May 28, 2009, 6:10:22 PM5/28/09
to DotNetDevelopment, VB.NET, C# .NET, ADO.NET, ASP.NET, XML, XML Web Services,.NET Remoting
Hello all,

I am tasked with creating a base exception handler that will handle a
bunch of clean-up that needs to happen based on the type of exception
thrown. So, for example, I will have (at least in my initial thoughts)
a base class like:

public abstract class BaseExceptionHandler
{

public void HandleException(Exception ex)
{
Do something based on exception type;
}
}

Then each inherited exception type will declare like:

public abstract class NewExceptionHandler : BaseExceptionHandler
{

Any new or overridden logic

}


Then the implementation needs to look like:

NewExceptionHandler exHandler = new NewExceptionHandler();

try
{
Whatever
}
catch (MissingDependencyException ex)
{
exHandler.HandleException(ex);
}
catch (DividebyzeroException ex)
{
exHandler.HandleException(ex);
}

How, given that all of these inherit from Sytem.Exception do I find
out the actual type of the exception thrown? I know I am missing
something obvious…

Thanks in advance!

rbr

Benj Nunez

unread,
May 28, 2009, 9:46:45 PM5/28/09
to DotNetDevelopment, VB.NET, C# .NET, ADO.NET, ASP.NET, XML, XML Web Services,.NET Remoting
I think you need to cast the Exception "ex" parameter.

Evaluate what the "ex" parameter holds and that would mean
declaring/anticipating what particular Exceptions might be thrown to
it like:


public void HandleException(Exception ex)
{
if ( (ex as MissingDependencyException ) != null) //
MissingDependencyException raised?
{
...do
stuff... // ..
then handle it...
}

if ( (ex as DividebyzeroException ) != null) //
DivideByZeroException raised?
{
...do different
stuff... // then handle
like...
}


// other possible exceptions define them here...

}



Regards,


Benj
Reply all
Reply to author
Forward
0 new messages