Home All Groups Group Topic Archive Search About

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

Author
30 Mar 2005 2:54 PM
l.woods
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

Author
30 Mar 2005 3:26 PM
Larry Lard
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
Author
30 Mar 2005 3:39 PM
Phill. W
"l.woods" <larry@NOSPAMlwoods.com> wrote in message
news:%23FxlThTNFHA.244@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.
Author
30 Mar 2005 3:40 PM
Herfried K. Wagner [MVP]
"l.woods" <larry@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/>
Author
30 Mar 2005 5:09 PM
Crouchie1998
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()
Author
30 Mar 2005 7:39 PM
Jay B. Harlow [MVP - Outlook]
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


Show quoteHide quote
"Crouchie1998" <crouchie1***@discussions.microsoft.com> wrote in message
news:eEm8UtUNFHA.244@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()
|
|
Author
31 Mar 2005 2:17 AM
Dennis
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!

Show quoteHide quote
"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" <crouchie1***@discussions.microsoft.com> wrote in message
> news:eEm8UtUNFHA.244@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()
> |
> |
>
>
>
Author
31 Mar 2005 3:23 PM
Jay B. Harlow [MVP - Outlook]
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


Show quoteHide quote
"Dennis" <Den***@discussions.microsoft.com> wrote in message
news:DC100983-E789-4A83-B172-8BDDEF11E696@microsoft.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>>
Author
1 Apr 2005 12:21 AM
Dennis
Thanks for your comments.  I"m just a hobbiest with VB.Net so I'm sure your
points are valid for Pros.

Show quoteHide quote
"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" <Den***@discussions.microsoft.com> wrote in message
> news:DC100983-E789-4A83-B172-8BDDEF11E696@microsoft.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>>
>
>
>
Author
30 Mar 2005 4:03 PM
Jay B. Harlow [MVP - Outlook]
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


Show quoteHide quote
"l.woods" <larry@NOSPAMlwoods.com> wrote in message
news:%23FxlThTNFHA.244@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
|
|
Author
4 Apr 2005 12:22 PM
l.woods
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

Show quoteHide quote
"Jay B. Harlow [MVP - Outlook]" <Jay_Harlow_***@msn.com> wrote in message
news:e2CysIUNFHA.3076@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" <larry@NOSPAMlwoods.com> wrote in message
> news:%23FxlThTNFHA.244@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
> |
> |
>
>
Author
4 Apr 2005 5:48 PM
Jay B. Harlow [MVP - Outlook]
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

Show quoteHide quote
"l.woods" <larry@NOSPAMlwoods.com> wrote in message
news:eMjbjDROFHA.1172@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]" <Jay_Harlow_***@msn.com> wrote in message
| news:e2CysIUNFHA.3076@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" <larry@NOSPAMlwoods.com> wrote in message
| > news:%23FxlThTNFHA.244@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
| > |
| > |
| >
| >
|
|