Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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:

 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?

  • Leaders
Posted
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.
--tim
  • *Gurus*
Posted

Volte is right. You can set up your handler to catch different types of exceptions as follows:

 

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

MVP, Visual Developer - .NET

 

Now you see why evil will always triumph - because good is dumb.

 

My free .NET Windows Forms Controls and Articles

Posted

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.

 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?

Posted

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.

          Catch exc As System.IO.timeout
       Catch exc As System.timeout
       Catch exc As System.timeoutexception

  • *Experts*
Posted

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.

 

Catch ex As System.ServiceProcess.TimeoutException

:-\

Posted

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.

Posted

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:

 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

  • *Experts*
Posted

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. :-\

  • *Experts*
Posted

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

"I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut
Posted

The GetType technique gets a LOT of data. But I don't see TimeOut anywhere. :cool:

Here's what I tried.

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

  • *Experts*
Posted

Try printing out the following:

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

"I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut
Posted

Good suggestion (thanks!) but no luck.

HashCode is still the only known method to make my program work.

I tested two error cases: 1. Port Not Open and 2. Timeout.

The only way to tell the difference between them is HashCode.

 

Here's the code I used:

 Catch exc As Exception
Dim ExceptionType As System.Type
ExceptionType = exc.GetType()        ' Error GetType
strErrMsg = exc.Message.ToString   ' Text Error Message.   
iHashCode = exc.Message.GetHashCode  ' Error HashCode 
Console.WriteLine("TEST1 GT=" & exc.GetType().ToString() _
               & ", H=" & iHashCode & ", M=" & strErrMsg) 

Here are the outputs from the two tests:

TEST1 GT=System.ApplicationException, H=-108330557, M=Please initialize and open port before using this method

TEST1 GT=System.ApplicationException, H=-1549478346, M=Read Error: Timeout error

 

I tested on two different machines, both Win2000 but different configurations. Identical results.

The HashCode numbers are constant, so this seems reliable.

 

Maybe this will remain one of those unanswered questions.

Posted

I don't see any answer in using GetType.

In both my test cases, exc.GetType() yielded NO distinguishing info.

It says only "System.ApplicationException"

 

I need to discriminate between TimeOuts and NON TimeOuts.

The only way I see to do this is through exc.Message.GetHashCode.

(or its even clumsier sibling exc.Message.ToString)

 

Is there something here that I'm missing? :confused:

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...