How to get Exception property (error code)

donaldc104

Freshman
Joined
Jan 4, 2003
Messages
32
I'm successfully trapping I/O exceptions. I'm getting the exception text MESSAGE ok, this works great. But I need a type CODE (integer). Here's the program:
Visual Basic:
 Catch exc As Exception
 strErrMsg = exc.Message.ToString '  Text Error Message.  Works great. 
 iErrCode = exc.Message.GetTypeCode  ' ??? Always=18 ??
How do I read the integer exception code?
 
btw. you're always returning 18 because the Message property of the exception class is always a string whose type enumeration always boils down to 18.
 
AFAIK, exceptions don't have numbers; they are actual classes,
rather than just an ID with a description.
 
Volte is right. You can set up your handler to catch different types of exceptions as follows:

Visual Basic:
Try
    System.IO.File.Delete("c:\test.txt")
Catch ex As System.IO.FileNotFoundException
    'Statements
Catch ex As System.IO.IOException
    'Statements
Catch ex As System.Exception
    'Statements
End Try
 
Thanks, I can see that this is the right way to approach it.
But my application need is slightly different.
Here's what I'm doing: I'm flushing all old residue out of a serial port. The process terminates when the READ times out. So I want to catch the timeout exceptions and handle them as normal. All other exceptions are true errors. Here's the code.
Visual Basic:
 Try  ' Flush the COMM buffer:  Read until no more chars.  
While (m_CommPort.Read(1) <> -1)  ' LOOP: Poll & read.
iChars += Chr(m_CommPort.InputStream(0)) ' 
iCharCount += 1  ' Count the number of Residue chars.  
lblEmStatus.Text = "Flushing..." & iCharCount & ", " & iChars
End While

             ' TimeOut exception means "flush is completed".
Catch exc As System.IO.IOException
 strErrMsg = exc.Message.ToString ' Text Error Message.  
 iHashCode = exc.Message.GetHashCode
 MsgBox("System.IO.IOException" & iHashCode & strErrMsg)
Catch exc As System.ApplicationException
 strErrMsg = exc.Message.ToString ' Text Error Message.   
  iHashCode = exc.Message.GetHashCode    ' -108330557=Not open,  -1549478346=Timeout
  MsgBox("System.ApplicationException " & iHashCode & strErrMsg)
Catch exc As Exception
 strErrMsg = exc.Message.ToString ' Text Error Message.   
  iHashCode = exc.Message.GetHashCode    ' -108330557=Not open,  -1549478346=Timeout
  MsgBox("Exception " & iHashCode & strErrMsg)
End Try

If iHashCode = -1549478346 Then  ' If TimeOut 
  WriteStatus("Comm" & iPort & " flushed OK. " & vbCrLf & iCharCount & " Chars Residue=" & "(" & iChars & ")")
Else
  WriteStatus("Comm Error #" & iHashCode & ", '" & strErrMsg & "'")
  End If

Observations:
1. The System.Exception seems to be the superset of all the others more specific types. So I think it's what I want to use here.
2. The HashCode seems to be the way to discriminate TimeOuts exceptions. But the actual numeric codes don't seem to be documented? Is it safe to use the obscure value "-1549478346" as I've done?
 
Using that value is pointless, it will change. Why aren't you just catching a TimeoutException?
 
How to catch a Timeout Exception?

"Catching a TimeoutException" is exactly what I want to do.
How do I do it?

I've searched the SDK docs. No luck (only obscure SQL timeouts). So far, my experiments have failed.
Visual Basic:
          Catch exc As System.IO.timeout
        Catch exc As System.timeout
        Catch exc As System.timeoutexception
 
I don't know if TimeoutException is what you're looking for; it's part
of the ServiceProcess namespace; you actually have to add a reference
to System.ServiceProcess.dll to your project for it to work. If it is
indeed what you want.

Visual Basic:
Catch ex As System.ServiceProcess.TimeoutException
:-\
 
How to reference ServiceProcess?

Yes, this is what I want.
Now, how do I add the reference to System.ServiceProcess.dll ?

I've searched the docs and it is what I want. But there are no examples. Sorry to ask such basic questions.
 
Right click on the 'References' item of your project in the Solution
Explorer and click 'Add Reference', then find it in the list.
 
I'm blocked. I right click on References but the pop-up list has "Add Reference" greyed out.
I dug through the framework docs but couldn't find any clues.
 
You're not trying to add it at runtime or something are you? That's
the only way I could make it greyed out on my comp. :-\
 
Immediate problem fixed - thanks! But I'm still having a problem.
No, I was not in run mode- something else was jammed up.
So I quit and restarted VisualStudio, and then I was able to add the DLL reference OK. :)

But the code does not seem to catch TimeOut exceptions. Here's what I have:
Visual Basic:
 Catch ex As System.ServiceProcess.TimeoutException
            strErrMsg = ex.Message.ToString ' Text Error Message.   
            iHashCode = ex.Message.GetHashCode
  Catch exc As Exception
            strErrMsg = exc.Message.ToString ' Text Error Message.   
            iHashCode = exc.Message.GetHashCode    ' -108330557=Not open,  -1549478346=Timeout
All exceptions are caught under "Exception" only.
The ServiceProcess.TimeoutException compiles OK but never executes.
Code re-sequencing doesn't have any effect.
Any ideas? :confused
 
Like I said, I'm not sure that the TimeoutException is what you want;
it looks like it doesn't have anything to do with the IO namespace
or anything similar; it's for service timeouts.

I'm sorry, I really don't know what to tell you. :-\
 
You can use exc.GetType() to see what the real exception type is. It might just be Exception, but it might be some other type that you're not trapping for.

Also, check if the InnerException property is null. If it's not, check what it's type is (using GetType()) as well. Some exceptions, if handled by managed code, may embed themselves as inner exceptions.

You don't want to rely on the GetHashCode method. The help file states that it is only guaranteed to be unique per instance of a class (and per AppDomain and some other things). If the exception doesn't have a more specific type (such as some kind of TimeoutException) then you might have to use the Message property. But check the exception type is first and see if that works :)

-ner
 
The GetType technique gets a LOT of data. But I don't see TimeOut anywhere. :cool:
Here's what I tried.
Visual Basic:
Catch exc As Exception
  Dim ExceptionType As System.Type
  ExceptionType = exc.GetType()
I set a breakpoint and did QuickWatch on ExceptionType (results below).
Lots of data but nothing seems useful.
I dug down several layers into the sub-items, but found only mud.

The Message.GetHashCode technique I'm using now seems to be reliable although clumsy.
I would prefer to use the "right" method, if only I could find it.

There has to be a TimeOut somewhere in this dark Microsoft cave. :cool:


- ExceptionType {System.RuntimeType} System.Type
+ [System.RuntimeType] {System.RuntimeType} System.RuntimeType
+ System.Reflection.MemberInfo {System.RuntimeType} System.Reflection.MemberInfo
DefaultLookup 28 System.Reflection.BindingFlags
+ FilterAttribute {System.Reflection.MemberFilter} System.Reflection.MemberFilter
+ FilterName {System.Reflection.MemberFilter} System.Reflection.MemberFilter
+ FilterNameIgnoreCase {System.Reflection.MemberFilter} System.Reflection.MemberFilter
+ Missing {System.Reflection.Missing} Object
Delimiter "."c Char
EmptyTypes {Length=0} System.Type()
+ defaultBinder {System.DefaultBinder} System.Reflection.Binder
+ valueType {System.RuntimeType} System.Type
+ enumType {System.RuntimeType} System.Type
+ objectType {System.RuntimeType} System.Type
MemberType TypeInfo System.Reflection.MemberTypes
DeclaringType Nothing System.Type
ReflectedType Nothing System.Type
+ GUID {System.Guid} System.Guid
+ DefaultBinder {System.DefaultBinder} System.Reflection.Binder
+ Module {System.Reflection.Module} System.Reflection.Module
+ Assembly {System.Reflection.Assembly} System.Reflection.Assembly
+ TypeHandle {System.RuntimeTypeHandle} System.RuntimeTypeHandle
FullName "System.ApplicationException" String
Namespace "System" String
AssemblyQualifiedName "System.ApplicationException, mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" String
+ BaseType {System.RuntimeType} System.Type
TypeInitializer Nothing System.Reflection.ConstructorInfo
Attributes 1056769 System.Reflection.TypeAttributes
IsNotPublic False Boolean
IsPublic True Boolean
IsNestedPublic False Boolean
IsNestedPrivate False Boolean
IsNestedFamily False Boolean
IsNestedAssembly False Boolean
IsNestedFamANDAssem False Boolean
IsNestedFamORAssem False Boolean
IsAutoLayout True Boolean
IsLayoutSequential False Boolean
IsExplicitLayout False Boolean
IsClass True Boolean
IsInterface False Boolean
IsValueType False Boolean
IsAbstract False Boolean
IsSealed False Boolean
IsEnum False Boolean
IsSpecialName False Boolean
IsImport False Boolean
IsSerializable True Boolean
IsAnsiClass True Boolean
IsUnicodeClass False Boolean
IsAutoClass False Boolean
IsArray False Boolean
IsByRef False Boolean
IsPointer False Boolean
IsPrimitive False Boolean
IsCOMObject False Boolean
IsGenericCOMObject False Boolean
HasElementType False Boolean
IsContextful False Boolean
IsMarshalByRef False Boolean
HasProxyAttribute False Boolean
+ UnderlyingSystemType {System.RuntimeType} System.Type
 
Try printing out the following:
Visual Basic:
Console.WriteLine(exc.GetType().ToString())

If it spits out anything other than "Exception" then that's the type you'll want. If it spits out "Exception", you're stuck using something else. If it's a managed class causing the error, I would think there's a more specific error... but who knows.

-nerseus
 
Back
Top