1

I traverse an array of bytes in a Try...Catch block. Something like this:

        Try
            For Each curByte In bytes
               'Do something with bytes.    
            Next
            Return encodedBytes
        Catch e As Exception
            'handle exception
        End Try

Randomly, my program will crash with an unhandled exception on the Next statement in the code block above. The exception is a StackOverflow in mscorlib.dll "unable to evaluate expression".

Why is my exception handling not handling the exception? I'm not sure I know where to begin trying to address this error.

kittyhawk
  • 688
  • 2
  • 11
  • 25
  • Do you do something in the exception other than have a comment there that says you are going to handle it? Try catches are not magical things where you just put them and all works well, you still have to do something in the exception to ensure your code doesn't come crashing down. – mituw16 May 20 '14 at 14:26
  • @mituw16: Not really true; a try catch with an empty catch is basically the old "`On Error Resume Next`" - it's not necessarily good or clean practise, but it'll work in many cases. – Dan Puzey May 20 '14 at 14:29

1 Answers1

1

A StackOverflowException cannot be caught, because it's a fundamentally breaking error that .NET generally can't recover from. That's why you're not catching the exception.

However, its cause is generally quite simple to determine: if you check your debugger at the point where the exception occurs and look at the callstack, you will typically see a recursive call (that is, the same method calling itself in a nested fashion). That's what's causing your exception, and you need to fix whatever logic is calling the recursive calls to address the issue.

Dan Puzey
  • 33,626
  • 4
  • 73
  • 96