473,724 Members | 2,284 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How can I cast an exception to its own type when I don't know what its type is?

Greetings!

I am working on an application that targets a Pocket PC running Windows CE
and SQL Server CE. Almost all functions in the application use a Try block
with a Catch block that looks like this:

Try
TryToDoIt()
Catch e as Exception
LogTheError(e)
Throw e
End Try

I would like a little more intelligence in this. I wrote a little routine
that generates a message showing expanded error information if the exception
is an SqlCeException. But I'd rather not add a second catch block to all of
the places where an SqlCeException could be thrown. For one thing, that
would be labor-intensive. For another thing, if this app is ever migrated
to a desktop, I'd have to add another catch block for SqlExceptions, and if
it's ported to Microsoft Access (God forbid), I'd have to add
OleDbExceptions , and so on.

So, I was hoping to do something like this:

Throw CType(e, TypeName(e))

so that when it got up to the next call in the call stack, it would be an
SqlCeException instead of just an Exception. Of course, that doesn't work,
since the type name has to be a type instead of a character string that
happens to hold a name type. Is there a way to do what I want?

Thanks very much!

Rob
Nov 21 '05 #1
4 2039
Rob,
Try
TryToDoIt()
Catch e as Exception
LogTheError(e)
Throw e
End Try If you use "Throw e" your stack trace will be lost, if you simple use
"Throw" the stack trace will be preserved.

Using either "Throw e" or "Throw" above will throw the type of exception
that you originally caught. If you caught a SqlCeException, it will throw a
SqlCeException. To throw a different type of exception you would need to use
"Throw New DifferentTypeOf Excpetion(e)". Note I am passing the exception
that I caught as an Inner Exception, so outer routines know what the real
exception was.
Note I normally do my logging in a global exception handler. I use
try/finally more then I use try/catch. I only use try/catch when there is
something specific that I need to do with the exception, otherwise I let my
global exception handlers handle the exception. In other words you don't
need to include Try/Catch in all of your routines, you only need to have
your Global Exception handler (below) to log your exceptions, then include
Try/Finally where you need to close resources & such.
Depending on the type of application you are creating, .NET has three
different global exception handlers.

For ASP.NET look at:
System.Web.Http Application.Err or event
Normally placed in your Global.asax file.

For console applications look at:
System.AppDomai n.UnhandledExce ption event
Use AddHandler in your Sub Main.

For Windows Forms look at:
System.Windows. Forms.Applicati on.ThreadExcept ion event
Use AddHandler in your Sub Main.

It can be beneficial to combine the above global handlers in your app, as
well as wrap your Sub Main in a try catch itself.

There is an article in the June 2004 MSDN Magazine that shows how to
implement the global exception handling in .NET that explains why & when you
use multiple of the above handlers...

http://msdn.microsoft.com/msdnmag/is...T/default.aspx

For example: In my Windows Forms apps I would have a handler attached to the
Application.Thr eadException event, plus a Try/Catch in my Main. The
Try/Catch in Main only catches exceptions if the constructor of the MainForm
raises an exception, the Application.Thr eadException handler will catch all

uncaught exceptions from any form/control event handlers.

Note David has some excellent comments on argument validation to your class
libraries. Especially if those class libraries are going to be used outside
of your current solution.

Hope this helps
Jay

"Rob Richardson" <no*******@n2ne t.net> wrote in message
news:ux******** ******@TK2MSFTN GP09.phx.gbl... Greetings!

I am working on an application that targets a Pocket PC running Windows CE
and SQL Server CE. Almost all functions in the application use a Try
block
with a Catch block that looks like this:

Try
TryToDoIt()
Catch e as Exception
LogTheError(e)
Throw e
End Try

I would like a little more intelligence in this. I wrote a little routine
that generates a message showing expanded error information if the
exception
is an SqlCeException. But I'd rather not add a second catch block to all
of
the places where an SqlCeException could be thrown. For one thing, that
would be labor-intensive. For another thing, if this app is ever migrated
to a desktop, I'd have to add another catch block for SqlExceptions, and
if
it's ported to Microsoft Access (God forbid), I'd have to add
OleDbExceptions , and so on.

So, I was hoping to do something like this:

Throw CType(e, TypeName(e))

so that when it got up to the next call in the call stack, it would be an
SqlCeException instead of just an Exception. Of course, that doesn't
work,
since the type name has to be a type instead of a character string that
happens to hold a name type. Is there a way to do what I want?

Thanks very much!

Rob

Nov 21 '05 #2
Just curious, but I use OnError GoTo's a lot and they seem to catch most all
exceptions (haven't had the joy of finding one that didn't get caught yet.)
What is the downside to using OnError GoTo's?

"Jay B. Harlow [MVP - Outlook]" wrote:
Rob,
Try
TryToDoIt()
Catch e as Exception
LogTheError(e)
Throw e
End Try

If you use "Throw e" your stack trace will be lost, if you simple use
"Throw" the stack trace will be preserved.

Using either "Throw e" or "Throw" above will throw the type of exception
that you originally caught. If you caught a SqlCeException, it will throw a
SqlCeException. To throw a different type of exception you would need to use
"Throw New DifferentTypeOf Excpetion(e)". Note I am passing the exception
that I caught as an Inner Exception, so outer routines know what the real
exception was.
Note I normally do my logging in a global exception handler. I use
try/finally more then I use try/catch. I only use try/catch when there is
something specific that I need to do with the exception, otherwise I let my
global exception handlers handle the exception. In other words you don't
need to include Try/Catch in all of your routines, you only need to have
your Global Exception handler (below) to log your exceptions, then include
Try/Finally where you need to close resources & such.
Depending on the type of application you are creating, .NET has three
different global exception handlers.

For ASP.NET look at:
System.Web.Http Application.Err or event
Normally placed in your Global.asax file.

For console applications look at:
System.AppDomai n.UnhandledExce ption event
Use AddHandler in your Sub Main.

For Windows Forms look at:
System.Windows. Forms.Applicati on.ThreadExcept ion event
Use AddHandler in your Sub Main.

It can be beneficial to combine the above global handlers in your app, as
well as wrap your Sub Main in a try catch itself.

There is an article in the June 2004 MSDN Magazine that shows how to
implement the global exception handling in .NET that explains why & when you
use multiple of the above handlers...

http://msdn.microsoft.com/msdnmag/is...T/default.aspx

For example: In my Windows Forms apps I would have a handler attached to the
Application.Thr eadException event, plus a Try/Catch in my Main. The
Try/Catch in Main only catches exceptions if the constructor of the MainForm
raises an exception, the Application.Thr eadException handler will catch all

uncaught exceptions from any form/control event handlers.

Note David has some excellent comments on argument validation to your class
libraries. Especially if those class libraries are going to be used outside
of your current solution.

Hope this helps
Jay

"Rob Richardson" <no*******@n2ne t.net> wrote in message
news:ux******** ******@TK2MSFTN GP09.phx.gbl...
Greetings!

I am working on an application that targets a Pocket PC running Windows CE
and SQL Server CE. Almost all functions in the application use a Try
block
with a Catch block that looks like this:

Try
TryToDoIt()
Catch e as Exception
LogTheError(e)
Throw e
End Try

I would like a little more intelligence in this. I wrote a little routine
that generates a message showing expanded error information if the
exception
is an SqlCeException. But I'd rather not add a second catch block to all
of
the places where an SqlCeException could be thrown. For one thing, that
would be labor-intensive. For another thing, if this app is ever migrated
to a desktop, I'd have to add another catch block for SqlExceptions, and
if
it's ported to Microsoft Access (God forbid), I'd have to add
OleDbExceptions , and so on.

So, I was hoping to do something like this:

Throw CType(e, TypeName(e))

so that when it got up to the next call in the call stack, it would be an
SqlCeException instead of just an Exception. Of course, that doesn't
work,
since the type name has to be a type instead of a character string that
happens to hold a name type. Is there a way to do what I want?

Thanks very much!

Rob


Nov 21 '05 #3
Hi Jay,

I use this code in new() of the form:
#If Not Debug Then

AddHandler Application.Thr eadException, AddressOf fErr.DisplayErr or

#End If

Were fErr.DisplayErr or(ByVal sender As Object, ByVal t As
System.Threadin g.ThreadExcepti onEventArgs) handles the unexpected exception.

The big advantage to me is:

- I don't have a lot of OnError GoTo code

- This code is part of a form i use derive from. Even if a add a new
function within my derived form, unexpected exceptions will be handeled
(logged).

Louis



"Dennis" <De****@discuss ions.microsoft. com> schreef in bericht
news:F0******** *************** ***********@mic rosoft.com...
Just curious, but I use OnError GoTo's a lot and they seem to catch most all exceptions (haven't had the joy of finding one that didn't get caught yet.) What is the downside to using OnError GoTo's?

"Jay B. Harlow [MVP - Outlook]" wrote:
Rob,
Try
TryToDoIt()
Catch e as Exception
LogTheError(e)
Throw e
End Try

If you use "Throw e" your stack trace will be lost, if you simple use
"Throw" the stack trace will be preserved.

Using either "Throw e" or "Throw" above will throw the type of exception
that you originally caught. If you caught a SqlCeException, it will throw a SqlCeException. To throw a different type of exception you would need to use "Throw New DifferentTypeOf Excpetion(e)". Note I am passing the exception
that I caught as an Inner Exception, so outer routines know what the real exception was.
Note I normally do my logging in a global exception handler. I use
try/finally more then I use try/catch. I only use try/catch when there is something specific that I need to do with the exception, otherwise I let my global exception handlers handle the exception. In other words you don't
need to include Try/Catch in all of your routines, you only need to have
your Global Exception handler (below) to log your exceptions, then include Try/Finally where you need to close resources & such.
Depending on the type of application you are creating, .NET has three
different global exception handlers.

For ASP.NET look at:
System.Web.Http Application.Err or event
Normally placed in your Global.asax file.

For console applications look at:
System.AppDomai n.UnhandledExce ption event
Use AddHandler in your Sub Main.

For Windows Forms look at:
System.Windows. Forms.Applicati on.ThreadExcept ion event
Use AddHandler in your Sub Main.

It can be beneficial to combine the above global handlers in your app, as well as wrap your Sub Main in a try catch itself.

There is an article in the June 2004 MSDN Magazine that shows how to
implement the global exception handling in .NET that explains why & when you use multiple of the above handlers...

http://msdn.microsoft.com/msdnmag/is...T/default.aspx

For example: In my Windows Forms apps I would have a handler attached to the Application.Thr eadException event, plus a Try/Catch in my Main. The
Try/Catch in Main only catches exceptions if the constructor of the MainForm raises an exception, the Application.Thr eadException handler will catch all
uncaught exceptions from any form/control event handlers.

Note David has some excellent comments on argument validation to your class libraries. Especially if those class libraries are going to be used outside of your current solution.

Hope this helps
Jay

"Rob Richardson" <no*******@n2ne t.net> wrote in message
news:ux******** ******@TK2MSFTN GP09.phx.gbl...
Greetings!

I am working on an application that targets a Pocket PC running Windows CE and SQL Server CE. Almost all functions in the application use a Try
block
with a Catch block that looks like this:

Try
TryToDoIt()
Catch e as Exception
LogTheError(e)
Throw e
End Try

I would like a little more intelligence in this. I wrote a little routine that generates a message showing expanded error information if the
exception
is an SqlCeException. But I'd rather not add a second catch block to all of
the places where an SqlCeException could be thrown. For one thing, that would be labor-intensive. For another thing, if this app is ever migrated to a desktop, I'd have to add another catch block for SqlExceptions, and if
it's ported to Microsoft Access (God forbid), I'd have to add
OleDbExceptions , and so on.

So, I was hoping to do something like this:

Throw CType(e, TypeName(e))

so that when it got up to the next call in the call stack, it would be an SqlCeException instead of just an Exception. Of course, that doesn't
work,
since the type name has to be a type instead of a character string that happens to hold a name type. Is there a way to do what I want?

Thanks very much!

Rob


Nov 21 '05 #4
Dennis,
There have been numerous discussions on using On Error Goto verses Try/Catch
& Try/Finally.

Try the following thread:

http://groups.google.com/groups?hl=e...sftngp04#link1

Title "What's with On Error Resume Next???" around 8 Nov 2001.

A handful of articles on the subject:

http://msdn.microsoft.com/vbasic/def...orhandling.asp
See the "Use Structured Exception Handling Rather Than On Error Statement"
section of:
http://msdn.microsoft.com/vstudio/us...tinternals.asp

See the "Exception Handling" section of:
http://msdn.microsoft.com/vstudio/us...tchperfopt.asp

Hope this helps
Jay

"Dennis" <De****@discuss ions.microsoft. com> wrote in message
news:F0******** *************** ***********@mic rosoft.com...
Just curious, but I use OnError GoTo's a lot and they seem to catch most
all
exceptions (haven't had the joy of finding one that didn't get caught
yet.)
What is the downside to using OnError GoTo's?

"Jay B. Harlow [MVP - Outlook]" wrote:
Rob,
> Try
> TryToDoIt()
> Catch e as Exception
> LogTheError(e)
> Throw e
> End Try

If you use "Throw e" your stack trace will be lost, if you simple use
"Throw" the stack trace will be preserved.

Using either "Throw e" or "Throw" above will throw the type of exception
that you originally caught. If you caught a SqlCeException, it will throw
a
SqlCeException. To throw a different type of exception you would need to
use
"Throw New DifferentTypeOf Excpetion(e)". Note I am passing the exception
that I caught as an Inner Exception, so outer routines know what the real
exception was.
Note I normally do my logging in a global exception handler. I use
try/finally more then I use try/catch. I only use try/catch when there is
something specific that I need to do with the exception, otherwise I let
my
global exception handlers handle the exception. In other words you don't
need to include Try/Catch in all of your routines, you only need to have
your Global Exception handler (below) to log your exceptions, then
include
Try/Finally where you need to close resources & such.
Depending on the type of application you are creating, .NET has three
different global exception handlers.

For ASP.NET look at:
System.Web.Http Application.Err or event
Normally placed in your Global.asax file.

For console applications look at:
System.AppDomai n.UnhandledExce ption event
Use AddHandler in your Sub Main.

For Windows Forms look at:
System.Windows. Forms.Applicati on.ThreadExcept ion event
Use AddHandler in your Sub Main.

It can be beneficial to combine the above global handlers in your app, as
well as wrap your Sub Main in a try catch itself.

There is an article in the June 2004 MSDN Magazine that shows how to
implement the global exception handling in .NET that explains why & when
you
use multiple of the above handlers...

http://msdn.microsoft.com/msdnmag/is...T/default.aspx

For example: In my Windows Forms apps I would have a handler attached to
the
Application.Thr eadException event, plus a Try/Catch in my Main. The
Try/Catch in Main only catches exceptions if the constructor of the
MainForm
raises an exception, the Application.Thr eadException handler will catch
all

uncaught exceptions from any form/control event handlers.

Note David has some excellent comments on argument validation to your
class
libraries. Especially if those class libraries are going to be used
outside
of your current solution.

Hope this helps
Jay

"Rob Richardson" <no*******@n2ne t.net> wrote in message
news:ux******** ******@TK2MSFTN GP09.phx.gbl...
> Greetings!
>
> I am working on an application that targets a Pocket PC running Windows
> CE
> and SQL Server CE. Almost all functions in the application use a Try
> block
> with a Catch block that looks like this:
>
> Try
> TryToDoIt()
> Catch e as Exception
> LogTheError(e)
> Throw e
> End Try
>
> I would like a little more intelligence in this. I wrote a little
> routine
> that generates a message showing expanded error information if the
> exception
> is an SqlCeException. But I'd rather not add a second catch block to
> all
> of
> the places where an SqlCeException could be thrown. For one thing,
> that
> would be labor-intensive. For another thing, if this app is ever
> migrated
> to a desktop, I'd have to add another catch block for SqlExceptions,
> and
> if
> it's ported to Microsoft Access (God forbid), I'd have to add
> OleDbExceptions , and so on.
>
> So, I was hoping to do something like this:
>
> Throw CType(e, TypeName(e))
>
> so that when it got up to the next call in the call stack, it would be
> an
> SqlCeException instead of just an Exception. Of course, that doesn't
> work,
> since the type name has to be a type instead of a character string that
> happens to hold a name type. Is there a way to do what I want?
>
> Thanks very much!
>
> Rob
>
>


Nov 21 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1403
by: Daylor | last post by:
first of all , PLEASE,say somthing..about my post. any reply will be nice to read. i have vb.app , with 2 appdomains. (now, in the next section , ill write "appdomain create" ,means a code in the appdomain is creating ) appdomain2 call appdomain 1 to create object of type "CCar" (the param is string ) the appdomain1 creating a object from assembly file. ( the object is of
3
3835
by: Ole Hanson | last post by:
Hi Trying to cast an exception to the correct type, I encounter some "strange" experiences: The compiler complains that the variable "t" is unknown in line 2 (Exception trueException = (t)exception; )! Why? I am getting the correct System.Type information in line 1 (Type t = exception.GetType();), but I can't cast my "trueException" to the correct type...
17
2673
by: Hazz | last post by:
In this sample code of ownerdraw drawmode, why does the '(ComboBox) sender' line of code need to be there in this event handler? Isn't cboFont passed via the managed heap, not the stack, into this cboFont_DrawItem event handler? Why does it need to be cast? -hazz ,................. cboFont.Items.AddRange(FontFamily.Families); } private void cboFont_DrawItem(object sender,
10
1787
by: Arjen | last post by:
Hello, Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidCastException: Specified cast is not valid. Line 176. Source Error:
5
3432
by: Nick Flandry | last post by:
I'm running into an Invalid Cast Exception on an ASP.NET application that runs fine in my development environment (Win2K server running IIS 5) and a test environment (also Win2K server running IIS 5), but fails on IIS 6 running on a Win2003 server. The web uses Pages derived from a custom class I wrote (which itself derives from Page) to provide some common functionality. The Page_Load handler the failing webpage starts out like this: ...
15
2251
by: David | last post by:
Hi, I have built a web application that will be a very high profile application. We had tested it, demonstrated it and shown that it all works. On a dress rehearsal run through, it failed spectacularly. I was so embarrassed and felt like killing the person that made it fail. However, when it goes live, IT MUST NOT FAIL. The system has a backoffice system that takes an excel spreadsheet from the
5
1396
by: UJ | last post by:
I have a try catch where I don't know all of the exceptions that can be thrown (I'm calling a web service in the try) and what I would ideally like to do is a catch all but then look at the type of exception that was thrown and decide what to do there. Because I don't know what all can be thrown I need to have sort of a generic exception where I can then say - what type is it ? and then process accordingly. I don't want to do a (Execption...
14
18748
by: budy_ludy | last post by:
Hi All, I am new to vb .net, I have an ArrayList and i store class objects in it, and later i want to retrieve each ArrayList items and type cast to the class, How can it be done ? I used CType for casting but it is throwing exception.
20
2905
by: raylopez99 | last post by:
Inspired by Chapter 8 of Albahari's excellent C#3.0 in a Nutshell (this book is amazing, you must get it if you have to buy but one C# book) as well as Appendix A of Jon Skeet's book, I am going through some LINQ queries. But how to cast? ( See the below, modified from somebody else's code. The problem is the query 'stops' (throws a cast exception) at "3", and never gets to "violet".
0
8868
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8741
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9243
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9160
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8063
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6689
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5996
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
2613
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2149
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.