rethrowing an error

Am I misunderstanding how to do this

I want to catch and then rethrow the error.

sub foo()
         try 
            bar
        Catch err As Exception
            Throw err
        Finally
            oServerReader.Close()
        End Try

end sub

I get a 'cast is invalid' on the Throw err line




Answer this question

rethrowing an error

  • Dan DeLaf

    Just create a new exception and reference the old exception's message.



    Catch err As Exception
                Throw New Exception(err.Message)
    End Try

     


    Dustin.


  • Tom Dixon

    I looks very odd.
    It would be helpful to see the problem if you post some real code.


  • Brachole

    OK, my very bad.

    It's not blowing up, it's telling me that the error is unhandled. i.e. My routine that it bubbles up to is not bothering to catch it, so that it eventually bubbles all the way up to the IDE - where it's reported as unhandled. Which is what it's supposed to do when I don't bother catching it, right

    I'm still learning this stuff.



  • C2O

    What version are you running
    I just tried this and the exception gets thrown as expected



    Private Sub CatchAndThrowError()
       Dim i As Integer = 1
       Dim s As String = "Foo"

       Try
          i = s
       Catch ex As Exception
          
    Throw ex
       End Try
    End Sub


     



  • PWStevens

     Dustin_H wrote:
    Just create a new exception and reference the old exception's message.



    Catch err As Exception
                Throw New Exception(err.Message)
    End Try

     


    Dustin.
    This does not work. I get an 'invalid index' error.


  • PCM2

     John Chen MS wrote:

    I looks very odd.
    It would be helpful to see the problem if you post some real code.


    No really, I just want the general syntax for now. All I want to do is allow my exception to bubble up to my top layer.

  • turbofreddan

    Correct - you still should handle the error in a try-catch block somewhere.
    For example the following code displays the message box when you click the button. If you called the CatchAndThrowError method without the Try-Catch you will get the unhandled exception


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Try
                CatchAndThrowError()
            Catch ex As Exception
                MsgBox("caught in the click")
            End Try

        End Sub


        Private Sub CatchAndThrowError()
            Dim i As Integer = 1
            Dim s As String = "Foo"
            Try
                i = s
            Catch ex As Exception
                Throw ex
            End Try
        End Sub


     



    hope that helps...



  • rethrowing an error