By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,709 Members | 2,116 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,709 IT Pros & Developers. It's quick & easy.

Determine whether an object is derived from another object

P: n/a
Hi,

How can I determine whether an object is derived from another object?

My specific example is that I have a CustomError class with several specific
error types that derive from it (CustomBuinessError, CustomTechnicalError,
etc.). The CustomError base class has some extra fields that I want to log
or display when an error is handled.

I know I can check for exception types in Catch blocks. But what about in
the global.asax Application_Error event? I retrieve the exception from the
Server object:

Exception exc = Server.GetLastError().GetBaseException();

1. How can I check for a specific exception type? ("is exc a
CustomTechnicalError?")

2. How can I check whether the exception derives from CustomError? In this
case I might want to print some fields from the CustomError (whether the
specific exception is CustomBuinessError, CustomTechnicalError, or
whatever).

Thanks for any pointers,

Mark
Jun 15 '07 #1
Share this Question
Share on Google+
9 Replies


P: n/a
On Fri, 15 Jun 2007 12:43:27 -0700, Mark Berry <ma***@sorrynoemail.com
wrote:
[...]
Exception exc = Server.GetLastError().GetBaseException();

1. How can I check for a specific exception type? ("is exc a
CustomTechnicalError?")

2. How can I check whether the exception derives from CustomError? In
this
case I might want to print some fields from the CustomError (whether the
specific exception is CustomBuinessError, CustomTechnicalError, or
whatever).
It sounds like you want the "is" operator.

For example:

if (exc is CustomError)
{
CustomError ce = (CustomError)exc;
// do some stuff with CustomError ce
}

Alternatively, the "as" operator:

CustomError ce = exc as CustomError;

if (ce != null)
{
// do some stuff with CustomError ce
}

Likewise the derived classes. Of course, all of the above assumes that
CustomError derives from Exception, which your post seems to imply it does.

Pete
Jun 15 '07 #2

P: n/a
"is" and "as", perhaps?
i.e.
if(error is CustomError) {...}
or
CustomError ce = error as CustomError;
if(ce!=null) {...}

(and ditto for CustomTechnicalError etc)

Personally I'd stick with the "Exception" suffix. In fact, I'd
probably stick to standard exceptions until I find an exceptional
exception; but there is a lot to be said for "ArgumentNullException",
"ObjectDisposedException", etc.

Marc

Jun 15 '07 #3

P: n/a
Use the is or as keywords.

if (x is string) { string y = x as string; use y as a string... }

So:

catch (Exception e)
{
if (e is CustomTechnicalError)
{
CustomTechnicalError cte = e as CustomTechnicalError;
... use cte.
}
}

Difference between as keyword and casting (i.e. (CustomTechnicalError) e) is
that "as" will return null; casting will throw an exception if e is not the
correct type.

If you are in control of the derived exception classes then you could always
add an override for the ToString method and just use:

catch (CustomError ce)
{
Log (ce.ToString());
}

As the ToString will call the respective virtual method on the class.

Each ToString override can build a string containing the information that
the specific instance provides which will i) make your code cleaner and ii)
provide easier extensibility should you add other exception classes.

HTH

- Andy

"Mark Berry" <ma***@sorrynoemail.comwrote in message
news:u5**************@TK2MSFTNGP04.phx.gbl...
Hi,

How can I determine whether an object is derived from another object?

My specific example is that I have a CustomError class with several
specific error types that derive from it (CustomBuinessError,
CustomTechnicalError, etc.). The CustomError base class has some extra
fields that I want to log or display when an error is handled.

I know I can check for exception types in Catch blocks. But what about in
the global.asax Application_Error event? I retrieve the exception from the
Server object:

Exception exc = Server.GetLastError().GetBaseException();

1. How can I check for a specific exception type? ("is exc a
CustomTechnicalError?")

2. How can I check whether the exception derives from CustomError? In this
case I might want to print some fields from the CustomError (whether the
specific exception is CustomBuinessError, CustomTechnicalError, or
whatever).

Thanks for any pointers,

Mark

Jun 15 '07 #4

P: n/a
"Mark Berry" <ma***@sorrynoemail.comwrote in message
news:u5**************@TK2MSFTNGP04.phx.gbl...
My specific example is that I have a CustomError class with several
specific error types that derive from it (CustomBuinessError,
CustomTechnicalError, etc.). The CustomError base class has some extra
fields that I want to log or display when an error is handled.
Don't use "is" or "as." Don't require the clients of an object to know which
specific class it belongs to.

Instead, use polymorphism. Create a virtual method that in the base class
which the derived classes override to do the "extra" stuff. In this case,
define one or more virtual methods like GetLogString() or
GetDisplayString().

When your clients need to know what specific class they're working with, you
end up with maintenance problems when you add a new derived class. You have
to search your entire codebase for all the logic that's conditional upon the
results of "is" or "as." By using polymorphism, you keep all the differences
in one place - in the class that's defining the differences.

"is" and "as" should be avoided wherever possible in favor of polymorphism.
Sometimes they're necessary, but it doesn't seem like this is one of those
times.

///ark
Jun 15 '07 #5

P: n/a
If GetLastError() really has to return Exception, then you will have to
interrogate the object to see if it's a CustomError, via "is." But don't
make the clients go any farther down in the hierarchy, if at all possible.

///ark
Jun 15 '07 #6

P: n/a
On Fri, 15 Jun 2007 14:13:26 -0700, Mark Wilden <mw*****@communitymtm.com>
wrote:
Don't use "is" or "as." Don't require the clients of an object to know
which
specific class it belongs to.

Instead, use polymorphism.
I do wholeheartedly agree with this advice. However, I'll point out that
it's not clear to me from the original post that this is practical in this
situation. I had the impression that he's receiving the exception in a
way that doesn't allow him to define the base type according to his own
type (that is, it always returns an Exception type object).

Sometimes you do need "is" or "as".

Pete
Jun 15 '07 #7

P: n/a
Thanks Marc. Actually I realized after typing the original post that I
should have been using the Exception suffix. Too lazy to retype ;).

I'm still new to .Net exception handling. I've been trying to follow and
extend Rob Bagby's webcast

http://blogs.msdn.com/bags/archive/2...e-and-ppt.aspx

I guess one argument for wrapping standard exceptions in custom exceptions
is that you can add contextual information e.g. current user name, etc. You
also get more granular control over how the Enterprise Library Application
Exception Block handles the exception, e.g ArgumentNullException might be a
validation error on a user form, but a system error if an object is
unexpectedly null.

Mark

"Marc Gravell" <ma**********@gmail.comwrote in message
news:11**********************@a26g2000pre.googlegr oups.com...
"is" and "as", perhaps?
i.e.
if(error is CustomError) {...}
or
CustomError ce = error as CustomError;
if(ce!=null) {...}

(and ditto for CustomTechnicalError etc)

Personally I'd stick with the "Exception" suffix. In fact, I'd
probably stick to standard exceptions until I find an exceptional
exception; but there is a lot to be said for "ArgumentNullException",
"ObjectDisposedException", etc.

Marc

Jun 15 '07 #8

P: n/a
Andy,

Thanks for the examples and especially for clarifying the use of "as" versus
a standard cast using parentheses.

Mark

"Andy Bates" <an**@ussdev.comwrote in message
news:%2****************@TK2MSFTNGP03.phx.gbl...
Use the is or as keywords.

if (x is string) { string y = x as string; use y as a string... }

So:

catch (Exception e)
{
if (e is CustomTechnicalError)
{
CustomTechnicalError cte = e as CustomTechnicalError;
... use cte.
}
}

Difference between as keyword and casting (i.e. (CustomTechnicalError) e)
is that "as" will return null; casting will throw an exception if e is not
the correct type.

If you are in control of the derived exception classes then you could
always add an override for the ToString method and just use:

catch (CustomError ce)
{
Log (ce.ToString());
}

As the ToString will call the respective virtual method on the class.

Each ToString override can build a string containing the information that
the specific instance provides which will i) make your code cleaner and
ii) provide easier extensibility should you add other exception classes.

HTH

- Andy

"Mark Berry" <ma***@sorrynoemail.comwrote in message
news:u5**************@TK2MSFTNGP04.phx.gbl...
>Hi,

How can I determine whether an object is derived from another object?

My specific example is that I have a CustomError class with several
specific error types that derive from it (CustomBuinessError,
CustomTechnicalError, etc.). The CustomError base class has some extra
fields that I want to log or display when an error is handled.

I know I can check for exception types in Catch blocks. But what about in
the global.asax Application_Error event? I retrieve the exception from
the Server object:

Exception exc = Server.GetLastError().GetBaseException();

1. How can I check for a specific exception type? ("is exc a
CustomTechnicalError?")

2. How can I check whether the exception derives from CustomError? In
this case I might want to print some fields from the CustomError (whether
the specific exception is CustomBuinessError, CustomTechnicalError, or
whatever).

Thanks for any pointers,

Mark


Jun 15 '07 #9

P: n/a
Wow guys thanks for all the answers and advice! I guess I found out where
all the smart people hang out ;).

I'm new to .Net exceptions and still trying to wrap my head around some
parts of it.

Yes, CustomException derives from Exception. I used the example of display
strings, but really I want to update an CustomException.ExceptionID property
that is defined as a GUID. I subsequently pass the exception to the
Enterprise Library (EL) Exception Handling Application Block, which logs the
exception including all its properties.

A little more background: this is a three-tier database application. I'm
trapping serious database exceptions in the Data Access Layer, wrapping them
in one of my CustomExceptions, logging them (via the EL), then re-throwing
them. (In the case of security exceptions, they are not re-thrown, but
rather a new dumbed-down exception is created and thrown.)

Eventually there will be various exception handlers in the business and
client tiers. However, for starters I am writing the "last chance" handler
in the global.asax Application_Error block. Without this, the full exception
is displayed to the user in the browser.

In the Application_Error block, I'll create a new CustomException and use
the EL to log it, then display a simplified message in the browser.

If the exception that I'm handling in the Application_Error block is one of
my custom exceptions, I want to use the ExceptionID from that
CustomException in the new exception. That way, potentially multiple
exceptions in the event log(s) can be identified as having the same cause.

However, exceptions percolating up to the Application_Error block are also
quite likely to be standard but unpredictable system exceptions (file locked
by another process, disk full, etc.). Those will also be wrapped and logged,
but they'll get a System.Guid.NewGuid() in their
CustomException.ExceptionID.

So that's the long answer of why I need to know if the "exc" I get is a
CustomException or not. My understanding is that using "is" or "as" is
unavoidable in this case?

NOW, this brings up another question: what if I decide that I need to do
different things for different types of exceptions, whether they are system
exceptions or derived from CustomException? For example, some exceptions may
not be fatal, so I can call Server.ClearError() and allow the user to
continue. However, others may mean I need to clean up and shut down. How
would I differentiate the different types of exceptions if not using "is" or
"as"? Or is it possible/advisable to use try - catch inside the
Application_Error block?

Thanks again for the helpful discussion,

Mark

"Mark Wilden" <mw*****@communitymtm.comwrote in message
news:%2****************@TK2MSFTNGP05.phx.gbl...
"Mark Berry" <ma***@sorrynoemail.comwrote in message
news:u5**************@TK2MSFTNGP04.phx.gbl...
>My specific example is that I have a CustomError class with several
specific error types that derive from it (CustomBuinessError,
CustomTechnicalError, etc.). The CustomError base class has some extra
fields that I want to log or display when an error is handled.

Don't use "is" or "as." Don't require the clients of an object to know
which specific class it belongs to.

Instead, use polymorphism. Create a virtual method that in the base class
which the derived classes override to do the "extra" stuff. In this case,
define one or more virtual methods like GetLogString() or
GetDisplayString().

When your clients need to know what specific class they're working with,
you end up with maintenance problems when you add a new derived class. You
have to search your entire codebase for all the logic that's conditional
upon the results of "is" or "as." By using polymorphism, you keep all the
differences in one place - in the class that's defining the differences.

"is" and "as" should be avoided wherever possible in favor of
polymorphism. Sometimes they're necessary, but it doesn't seem like this
is one of those times.

///ark

Jun 15 '07 #10

This discussion thread is closed

Replies have been disabled for this discussion.