views:

433

answers:

2

I ran into an interesting dilemna today. I have a function that handles information and checks for duplicate values, then returns the next number that is not a duplicate. So, I have something like this:

Public Function GetNextNonDuplicateNumber(NumberToCheck as Long) as Long

      //the non-duplicate the function will return
      Dim NonDuplicate as Long



         'duplicate
      If CheckForDuplicate(NumberToCheck) = True Then
              Throw New DuplicateException()

           'not duplicte
          Else

              NonDuplicate = NumberToCheck

      End If

End Function

Then at the bottom of the function I have a catch block that handles the duplicate by incrementing until I don't have a duplicate any more, like this:

Catch ex as DuplicateException

   NonDuplicate = IncrementToNonDuplicateValue(NumberToCheck)

    Throw ex

  Return NonDuplicate

End Function

As you can see, I want to handle the exception specifically, but I also want to throw it when I'm done because I want to alert other code outside the function. The problem is that simply throwing it exits out of the function with a null value. Am I thinking about a try/catch the wrong way, or is there a way around this? Thanks for the help!

+2  A: 

If you caught an exception and recovered from it (with your IncrementToNonDuplicate...) then there is no reason to throw an exception anymore. Code between catch and end try should just clean the resources like closing a file or datareader if you will rethrow it.

You could rather return a structure that contains NonDuplicate value and required information about errors in function. Other way would be to throw a custom exception that will contain information like "Invalid number: it should be...)

Hugo Riley
A: 

you can return a boolean indicating if a duplicate is found, and change parameter to be passed in by reference so you can update the value.

Public Function GetNextNonDuplicateNumber(ByRef NonDupeNumber as Long) as Boolean
elan