What to return from a function if an exception is thrown?

Hi,

I have a function that I call to create an arrayList of objects. I've enclosed it in a 'Try...Catch' block. I return the arrayList at the end of the 'Try' and in the 'Catch' I display a messagebox with whatever the exception is in it's message.

I'm getting a warning that 'Function blah doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.'

So, I'm just wondering what I'm supposed to do to get rid of this warning? Do I return an empty arrayList and then test for that in the function call? Or is there a better solution?

Thanks,
Chris
squeakyloboyAsked:
Who is Participating?
 
bruintjeConnect With a Mentor Commented:
sorry i should've been more clear

Function
Dim tmpVal as something

    Try
       'do some processsing here
      tmpVal =

    Catch ex As Exception
       'do some handling here

    Finally
       'this will always run so put the return value here
       'test if tmpVal is still nothing then set it to nothing
       'tmpVal = Nothing

    End Try
   
    return tmpVal

end function

in the calling function you can test for nothing as input from the function and handle it accordingly
0
 
bruintjeCommented:
Hi squeakyloboy,
----------

a way is to add a finally part to the try catch

Function

    Try

    Catch ex As Exception

    Finally
'this will always run so put the return value here
    End Try

end function

----------
bruintje
share what you know, learn what you don't
0
 
squeakyloboyAuthor Commented:
Hi bruintje, thanks for the reply.

Ok, I've moved the return as follows:

        Finally

            Return tracksList

        End Try

...but I get the error 'Branching out of a 'Finally' is not valid'.

Any ideas?
0
 
squeakyloboyAuthor Commented:
Ah, got it. That's kinda what I thought but it's good to confirm it.

Thanks a lot!
Chris
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.