473,326 Members | 2,438 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,326 software developers and data experts.

How can I determine WHICH exception I got in my CATCH?

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 more specific. I can't find any property of the exception
object that tells me WHICH one it is.

TIA,

Larry Woods
Nov 21 '05 #1
11 1963

l.woods wrote:
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 more specific. I can't find any property of the exception object that tells me WHICH one it is.


Its type.

If TypeOf ex Is SpecificExceptionIWant Then
....

Concrete example:

Dim a As Integer = 1, b As Integer = 0, c As Integer

Try
c = a \ b
Catch ex As Exception
If TypeOf ex Is DivideByZeroException Then
MsgBox("No surprise")
Else
MsgBox("Something WEIRD")
End If
End Try

This is exactly like looking for specific Err.Number's in VB6, which is
what I suspect you are looking for.
--
Larry Lard
Replies to group please

Nov 21 '05 #2
"l.woods" <la***@NOSPAMlwoods.com> schrieb:
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 more specific. I can't find any property of the
exception
object that tells me WHICH one it is.


\\\
If TypeOf ex Is FooException Then
...
ElseIf TypeOf ex Is GooException Then
...
....
End If
///

- or -

\\\
Select Case True
Case TypeOf ex Is FooException
...
Case TypeOf ex Is GooException
...
...
End Select
///

Note that FxCop will complain about 'Catch' blocks which catch the generic
exception type. However, this rule is controversial and may be
altered/removed. German article on this issue:

Mythos: Catch( Exception) ist böse
<URL:http://www.die.de/blog/PermaLink.aspx?guid=c0d9a5d0-b12d-4995-8447-94040a932dc9>

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Nov 21 '05 #3
"l.woods" <la***@NOSPAMlwoods.com> wrote in message
news:%2***************@tk2msftngp13.phx.gbl...
I want to set up my CATCH for a specific exception,
You can explicitly catch any sort of Exception you want, as in

Catch nrx as NullReferenceException
Catch ax as ArgumentException
Catch ex as Exception

but the "trick" is catch the "smallest" one first - When an Exception
occurs, VB will use the /most appropriate/ exception handler.
but I really don't know which one of the multitude that it is.
Ah.
I can't find any property of the exception object that tells me
WHICH one it is.


That's because there isn't one - you can simply examine the Type
of the Exception object directly:

Catch ex as Exception
If TypeOf ex Is ArgumentException Then
DirectCast( ex, ArgumentException).thingamydoodle
End If

HTH,
Phill W.
Nov 21 '05 #4
Larry,
In addition to Larry's sample of:

Try
DoSomething()
Catch ex As Exception
If TypeOf ex Is SystemException Then
' got a system exception
ElseIf TypeOf ex Is ApplicationException Then
' got a application exception
Else
' got another kind of exception
End If
End Try

I prefer:

Try
DoSomething()
Catch ex As SystemException
' got a system exception
Catch ex As ApplicationException
' got a application exception
Catch ex As Exception
' got another kind of exception
End Try

Remember on both to list derived exceptions before base exceptions. As the
first class that matches is the handler that will be used.
I prefer the second, as its 'cleaner' and it allows you to only catch the
specific exception you want, while ignoring unwanted exceptions. For
example:

Try
DoSomething()
Catch ex As FileNotFoundException
' got a file not found exceptoin
End Try

Will only catch FileNotFoundExceptions, other exceptions will continue
upward to another exception handler...

Another useful tidbit to limit what exceptions are caught is the When
clause. For example:

Dim request As HttpWebRequest
Dim response As HttpWebResponse
Try
response = DirectCast(request.GetResponse(), HttpWebResponse)
Catch ex As WebException When TypeOf ex.Response Is HttpWebResponse
response = DirectCast(ex.Response, HttpWebResponse)
End Try

The catch block will only handle WebExceptions that have a Reponse type of
HttpWebResponse.

Hope this helps
Jay
"l.woods" <la***@NOSPAMlwoods.com> wrote in message
news:%2***************@tk2msftngp13.phx.gbl...
|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 more specific. I can't find any property of the
exception
| object that tells me WHICH one it is.
|
| TIA,
|
| Larry Woods
|
|
Nov 21 '05 #5
Try
....
Catch ex As Exception

MessageBox.Show(ex.ToString)

End Try

That will tell you exactly which type of exception you have then you can
catch the exceptions more precisely.

Try
....
Catch ex As IO.FileIOException
' Handle file access error
Catch exx As Exception
' Handle all other errors
End Try

You can also use 'IndexOf' too if you know the exact error message. 'Example
Only' below:

Dim sr As IO.StreamReader

Try
sr = New IO.StreamReader("C:\zzzzz.txt")
sr.Read()
Catch ex As Exception
If ex.ToString.IndexOf("Could not find file") > 0 Then
MessageBox.Show("File Not Found")
End If
End Try

If Not sr Is Nothing Then sr.Close()
Nov 21 '05 #6
Crouchie,
| You can also use 'IndexOf' too if you know the exact error message.
'Example
| Only' below:
I would not recommend using this approach as it does not localize very well.

Hope this helps
Jay
"Crouchie1998" <cr**********@discussions.microsoft.com> wrote in message
news:eE*************@TK2MSFTNGP12.phx.gbl...
| Try
| ...
| Catch ex As Exception
|
| MessageBox.Show(ex.ToString)
|
| End Try
|
| That will tell you exactly which type of exception you have then you can
| catch the exceptions more precisely.
|
| Try
| ...
| Catch ex As IO.FileIOException
| ' Handle file access error
| Catch exx As Exception
| ' Handle all other errors
| End Try
|
| You can also use 'IndexOf' too if you know the exact error message.
'Example
| Only' below:
|
| Dim sr As IO.StreamReader
|
| Try
| sr = New IO.StreamReader("C:\zzzzz.txt")
| sr.Read()
| Catch ex As Exception
| If ex.ToString.IndexOf("Could not find file") > 0 Then
| MessageBox.Show("File Not Found")
| End If
| End Try
|
| If Not sr Is Nothing Then sr.Close()
|
|
Nov 21 '05 #7
Jay, this has no relevance to this thread but I noted that sr was returned by
VB.Net as nothing as are other VB.Net varibles that can't be initialized.
This got me into the habit of returning nothing for reference type variables
from some of my routines when something couldn't be found. For example, I do
some work with reading and manipulating ID3 tags from mp3 files and when my
routines can't find a tag item, the string is returned as nothing. However,
in every tag, I must check for either the tag isn't there or the text
associated with the tag is "". This is what made me wish that things like
String.trim(x) would just return nothing when x is nothing!

"Jay B. Harlow [MVP - Outlook]" wrote:
Crouchie,
| You can also use 'IndexOf' too if you know the exact error message.
'Example
| Only' below:
I would not recommend using this approach as it does not localize very well.

Hope this helps
Jay
"Crouchie1998" <cr**********@discussions.microsoft.com> wrote in message
news:eE*************@TK2MSFTNGP12.phx.gbl...
| Try
| ...
| Catch ex As Exception
|
| MessageBox.Show(ex.ToString)
|
| End Try
|
| That will tell you exactly which type of exception you have then you can
| catch the exceptions more precisely.
|
| Try
| ...
| Catch ex As IO.FileIOException
| ' Handle file access error
| Catch exx As Exception
| ' Handle all other errors
| End Try
|
| You can also use 'IndexOf' too if you know the exact error message.
'Example
| Only' below:
|
| Dim sr As IO.StreamReader
|
| Try
| sr = New IO.StreamReader("C:\zzzzz.txt")
| sr.Read()
| Catch ex As Exception
| If ex.ToString.IndexOf("Could not find file") > 0 Then
| MessageBox.Show("File Not Found")
| End If
| End Try
|
| If Not sr Is Nothing Then sr.Close()
|
|

Nov 21 '05 #8
Dennis,
| Jay, this has no relevance to this thread
I take it you mean your comments has no relevance to which exception. ;-)

| but I noted that sr was returned by
| VB.Net as nothing
What is "sr returned by VB.NET"?

| as are other VB.Net varibles that can't be initialized.
All VB.NET variables can be initialized! can you give me an example of one
that cannot?

| This got me into the habit of returning nothing for reference type
variables
| from some of my routines when something couldn't be found.
Yes returning Nothing is handy sometimes, returning a "NullObject" is
usually handier, aka Special Case pattern.
http://www.martinfowler.com/eaaCatalog/specialCase.html

| For example, I do
| some work with reading and manipulating ID3 tags from mp3 files and when
my
| routines can't find a tag item, the string is returned as nothing.
Do you need to know specifically if its not found? If I don't specifically
need to know I will return String.Empty rather then Nothing, allowing me to
use instance methods on the string as normal. I would consider throwing an
exception for not found, especially if not found does not allow me to
continue. I would consider returning Nothing if I needed to know
specifically, but would then rather quickly change it to String.Empty to
continue processing... I would consider using ByRef parameters to return a
non-Nothing string & an boolean indicator if its found or not, however this
feels like returning an object other then string (such as a ID3Tag class
that I defined) that encapsulated the found string or String.Empty the fact
none was found.

Hope this helps
Jay
"Dennis" <De****@discussions.microsoft.com> wrote in message
news:DC**********************************@microsof t.com...
| Jay, this has no relevance to this thread but I noted that sr was returned
by
| VB.Net as nothing as are other VB.Net varibles that can't be initialized.
| This got me into the habit of returning nothing for reference type
variables
| from some of my routines when something couldn't be found. For example, I
do
| some work with reading and manipulating ID3 tags from mp3 files and when
my
| routines can't find a tag item, the string is returned as nothing.
However,
| in every tag, I must check for either the tag isn't there or the text
| associated with the tag is "". This is what made me wish that things like
| String.trim(x) would just return nothing when x is nothing!
|
<<xnip>>
Nov 21 '05 #9
Thanks for your comments. I"m just a hobbiest with VB.Net so I'm sure your
points are valid for Pros.

"Jay B. Harlow [MVP - Outlook]" wrote:
Dennis,
| Jay, this has no relevance to this thread
I take it you mean your comments has no relevance to which exception. ;-)

| but I noted that sr was returned by
| VB.Net as nothing
What is "sr returned by VB.NET"?

| as are other VB.Net varibles that can't be initialized.
All VB.NET variables can be initialized! can you give me an example of one
that cannot?

| This got me into the habit of returning nothing for reference type
variables
| from some of my routines when something couldn't be found.
Yes returning Nothing is handy sometimes, returning a "NullObject" is
usually handier, aka Special Case pattern.
http://www.martinfowler.com/eaaCatalog/specialCase.html

| For example, I do
| some work with reading and manipulating ID3 tags from mp3 files and when
my
| routines can't find a tag item, the string is returned as nothing.
Do you need to know specifically if its not found? If I don't specifically
need to know I will return String.Empty rather then Nothing, allowing me to
use instance methods on the string as normal. I would consider throwing an
exception for not found, especially if not found does not allow me to
continue. I would consider returning Nothing if I needed to know
specifically, but would then rather quickly change it to String.Empty to
continue processing... I would consider using ByRef parameters to return a
non-Nothing string & an boolean indicator if its found or not, however this
feels like returning an object other then string (such as a ID3Tag class
that I defined) that encapsulated the found string or String.Empty the fact
none was found.

Hope this helps
Jay
"Dennis" <De****@discussions.microsoft.com> wrote in message
news:DC**********************************@microsof t.com...
| Jay, this has no relevance to this thread but I noted that sr was returned
by
| VB.Net as nothing as are other VB.Net varibles that can't be initialized.
| This got me into the habit of returning nothing for reference type
variables
| from some of my routines when something couldn't be found. For example, I
do
| some work with reading and manipulating ID3 tags from mp3 files and when
my
| routines can't find a tag item, the string is returned as nothing.
However,
| in every tag, I must check for either the tag isn't there or the text
| associated with the tag is "". This is what made me wish that things like
| String.trim(x) would just return nothing when x is nothing!
|
<<xnip>>

Nov 21 '05 #10
Thanks to all....

In my situation, what I was looking for will probably be solved by the
"MessageBox.Show (ex.ToString). My problem was that I was getting an
exception, and I wanted to know exactly WHICH exception it was so that I
could recode and check for that exception specifically. The ex.ToSting will
hopefully give that information to me.

Larry Woods

"Jay B. Harlow [MVP - Outlook]" <Ja************@msn.com> wrote in message
news:e2**************@tk2msftngp13.phx.gbl...
Larry,
In addition to Larry's sample of:

Try
DoSomething()
Catch ex As Exception
If TypeOf ex Is SystemException Then
' got a system exception
ElseIf TypeOf ex Is ApplicationException Then
' got a application exception
Else
' got another kind of exception
End If
End Try

I prefer:

Try
DoSomething()
Catch ex As SystemException
' got a system exception
Catch ex As ApplicationException
' got a application exception
Catch ex As Exception
' got another kind of exception
End Try

Remember on both to list derived exceptions before base exceptions. As the
first class that matches is the handler that will be used.
I prefer the second, as its 'cleaner' and it allows you to only catch the
specific exception you want, while ignoring unwanted exceptions. For
example:

Try
DoSomething()
Catch ex As FileNotFoundException
' got a file not found exceptoin
End Try

Will only catch FileNotFoundExceptions, other exceptions will continue
upward to another exception handler...

Another useful tidbit to limit what exceptions are caught is the When
clause. For example:

Dim request As HttpWebRequest
Dim response As HttpWebResponse
Try
response = DirectCast(request.GetResponse(), HttpWebResponse)
Catch ex As WebException When TypeOf ex.Response Is HttpWebResponse
response = DirectCast(ex.Response, HttpWebResponse)
End Try

The catch block will only handle WebExceptions that have a Reponse type of
HttpWebResponse.

Hope this helps
Jay
"l.woods" <la***@NOSPAMlwoods.com> wrote in message
news:%2***************@tk2msftngp13.phx.gbl...
|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 more specific. I can't find any property of the
exception
| object that tells me WHICH one it is.
|
| TIA,
|
| Larry Woods
|
|

Nov 21 '05 #11
Larry,
As you found using Exception.ToString is useful to determine which exception
you need to catch.

I normally use Exception.Message when showing messages to user's

I normally use Exception.ToString() when logging the message for later
diagnosis of the problem.

Hope this helps
Jay

"l.woods" <la***@NOSPAMlwoods.com> wrote in message
news:eM**************@TK2MSFTNGP12.phx.gbl...
| Thanks to all....
|
| In my situation, what I was looking for will probably be solved by the
| "MessageBox.Show (ex.ToString). My problem was that I was getting an
| exception, and I wanted to know exactly WHICH exception it was so that I
| could recode and check for that exception specifically. The ex.ToSting
will
| hopefully give that information to me.
|
| Larry Woods
|
| "Jay B. Harlow [MVP - Outlook]" <Ja************@msn.com> wrote in message
| news:e2**************@tk2msftngp13.phx.gbl...
| > Larry,
| > In addition to Larry's sample of:
| >
| > Try
| > DoSomething()
| > Catch ex As Exception
| > If TypeOf ex Is SystemException Then
| > ' got a system exception
| > ElseIf TypeOf ex Is ApplicationException Then
| > ' got a application exception
| > Else
| > ' got another kind of exception
| > End If
| > End Try
| >
| > I prefer:
| >
| > Try
| > DoSomething()
| > Catch ex As SystemException
| > ' got a system exception
| > Catch ex As ApplicationException
| > ' got a application exception
| > Catch ex As Exception
| > ' got another kind of exception
| > End Try
| >
| > Remember on both to list derived exceptions before base exceptions. As
the
| > first class that matches is the handler that will be used.
| >
| >
| > I prefer the second, as its 'cleaner' and it allows you to only catch
the
| > specific exception you want, while ignoring unwanted exceptions. For
| > example:
| >
| > Try
| > DoSomething()
| > Catch ex As FileNotFoundException
| > ' got a file not found exceptoin
| > End Try
| >
| > Will only catch FileNotFoundExceptions, other exceptions will continue
| > upward to another exception handler...
| >
| > Another useful tidbit to limit what exceptions are caught is the When
| > clause. For example:
| >
| > Dim request As HttpWebRequest
| > Dim response As HttpWebResponse
| > Try
| > response = DirectCast(request.GetResponse(), HttpWebResponse)
| > Catch ex As WebException When TypeOf ex.Response Is HttpWebResponse
| > response = DirectCast(ex.Response, HttpWebResponse)
| > End Try
| >
| > The catch block will only handle WebExceptions that have a Reponse type
of
| > HttpWebResponse.
| >
| > Hope this helps
| > Jay
| >
| >
| > "l.woods" <la***@NOSPAMlwoods.com> wrote in message
| > news:%2***************@tk2msftngp13.phx.gbl...
| > |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 more specific. I can't find any property of the
| > exception
| > | object that tells me WHICH one it is.
| > |
| > | TIA,
| > |
| > | Larry Woods
| > |
| > |
| >
| >
|
|
Nov 21 '05 #12

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

Similar topics

24
by: Steven T. Hatton | last post by:
If I understand correctly, I have no assurance that I can determine the type of a simple class instance thrown as an exception unless I explicitly catch it by name. (non-derived classes having no...
3
by: Dean Slindee | last post by:
I have a exception handling class that could be called from either a windows project app or a console project app. Is there any way for this class to determine which type of app called it without...
4
by: Stan | last post by:
When a webservice is called through BeginInvoke asynchrously and an exception is thrown, this exception is not propagated to the client (obviously). Asynch client simply does not care about it. ...
7
by: semedao | last post by:
Hi all, I view many posts about this issue , the connected property does not tell us the current status of the socket. based on couple of suggestions of msdn , and some article here , I try to...
9
by: Mark Berry | last post by:
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...
3
by: abhimanyu | last post by:
I have a method Marshal.IsComObject(...) that returns TRUE if an object is a COM object. I have an object of Excel.Worksheet that I released using Marshal.ReleaseComObject(...). I want to iterate...
7
by: Ralf Jansen | last post by:
For logging purposes i want to determine if the current executing code is running in an ~exceptionhandling context~. I need no details about the exception just if an exception has been thrown and...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
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...
1
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...
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)...
1
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...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
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.