473,320 Members | 2,020 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Determine whether an object is derived from another object

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
9 3751
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
"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
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
"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
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

18
by: Christopher W. Douglas | last post by:
I am writing a VB.NET application in Visual Studio 2003. I have written a method that handles several events, such as closing a form and changing the visible status of a form. I have some code...
5
by: Jeff Greenberg | last post by:
Not an experienced c++ programmer here and I've gotten myself a bit stuck. I'm trying to implement a class lib and I've run into a sticky problem that I can't solve. I'd appreciate any help that I...
4
by: John Baro | last post by:
I need to determine which fonts are human readable. Webdings, wingdings etc.. are not. Is there any easy way to accomplish this? Cheers JB
5
by: Chris Capon | last post by:
Is there any way to cast a base class object to a derived class datatype when the derived class adds no new fields nor alters the object allocation in any way? The scenario would be where you...
11
by: l.woods | last post by:
I want to set up my CATCH for a specific exception, but I really don't know which one of the multitude that it is. I am getting the exception now with Catch ex as Exception but I want to be...
11
by: S. I. Becker | last post by:
Is it possible to determine if a function has been overridden by an object, when I have a pointer to that object as it's base class (which is abstract)? The reason I want to do this is that I want...
6
by: noel.hunt | last post by:
I have a base class, PadRcv, with virtual functions. User code will derive from this class and possibly supply it's own functions to override the base class virtual functions. How can I test that...
6
by: wink | last post by:
I'd like to determine if a method has been overridden as was asked here: http://www.velocityreviews.com/forums/t564224-determining-whether-a-derived-class-overrides-a-virtual-memberfunction.html...
10
by: blangela | last post by:
If I pass a base class object by reference (likely does not make a difference here that it is passed by reference) as a parameter to a derived class member function, the member function is not...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.