Balaji V
Balaji V

Reputation: 109

Nested Try-Catch: Throw an exception for outer try catch loop

I have defined 2 custom exceptions like

Public Class SkipException
   Inherits System.ApplicationException
End Class

Public Class NoRecordFoundException
   Inherits System.ApplicationException
End Class

In my code the scenarios are 1. Data causes general exception 2. I dont have the data 3. Exception I have handled already

Try
'Some code here
    Try
       ''Do some code
       ''Cant find the record
       If i = 0 then
           Throw NoRecordFoundException
       End if 
    Catch ex as Exception

    End Try

    Try
        ''Cant do nothing so just skip
        If CantDoNothing then
           Throw SkipException
        End if
    Catch ex as Exception

    End Try
Catch SkipException
  ''Some code here
Catch NoRecordFoundException
  '' some code here
Catch ex as Exception
   ''Handle regular exception
End Try

So will this work? Will the exception go to the outer handling and not the inner catch?

Right now, Im re-Throwing the exception to get it working.

Upvotes: 0

Views: 1815

Answers (1)

djv
djv

Reputation: 15774

Just handle the specific exception and rethrow. The following Catch ex as Exception will ignore exceptions caught before it.

Try
    Try
        Throw New NoRecordFoundException()
    Catch ex As NoRecordFoundException
        Throw
    Catch ex As Exception
        ' nothing happens here
    End Try
Catch ex As NoRecordFoundException
    ' handled here
Catch ex As Exception
    ' nothing happens here
End Try

Upvotes: 2

Related Questions