0

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.

4
  • 2
    Not right now, you catch all exception and do nothing with them. I'm wondering if you really need exception. Maybe you just need a status variable or a return value from a method. Commented Oct 18, 2019 at 18:10
  • 1
    Throw New NoRecordFoundException(). The internal Catch will catch it (if it was doing something with it). You could have something like Throw new Exception("Inner", New SkipException()) and in Catch ex As Exception, if ex.InnerException is SkipException then Throw ex.InnerException. This will be caught by the external Catch SkipException. But, the internal Try block could just have a Finally block instead of a Catch block, so the external Catch blocks would catch all the exceptions. Commented Oct 18, 2019 at 18:12
  • 1
    While the answer below seems correct, I also agree that exceptions might not be the right tool for this. Better designed If blocks or a few variable to track the current state might be more appropriate. Commented Oct 18, 2019 at 19:35
  • Thanks for all the explanations. The "Re-throw" was a simple answer! Commented Oct 27, 2019 at 21:52

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.