Click here to Skip to main content
16,016,613 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have been trying t learn how to create my own funtions and need a little help. On everyone i have created i get similar warnings like this:

Warning	1	Function 'GetFileContents' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.	C:\Users\Zachary\Desktop\Synergy.079s\Synergy\Modules\Updating.vb	42	5	Synergy


Is this something i shouldn't worry about since it works or should i be adding something to the function for a safety? help would be great.


Public Function GetFileContents(ByVal FullPath As String, Optional ByRef ErrInfo As String = "") As String

    Dim strContents As String
    Dim objReader As StreamReader

    Try
        objReader = New StreamReader(FullPath)
        strContents = objReader.ReadToEnd()
        objReader.Close()
        Return strContents
    Catch Ex As Exception
        ErrInfo = Ex.Message
    End Try

End Function
Posted

1 solution

The Catch part of your code does not contain a return statement.

I would change your code and more the return statement at the end of the function.
VB
Public Function GetFileContents(ByVal FullPath As String, Optional ByRef ErrInfo As String = "") As String

    Dim strContents As String = ""
    Dim objReader As StreamReader

    Try
        objReader = New StreamReader(FullPath)
        strContents = objReader.ReadToEnd()
        objReader.Close()
    Catch Ex As Exception
        ErrInfo = Ex.Message
    End Try

    Return strContents

End Function

This way all execution paths return a value.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 4-Mar-12 19:29pm    
Correct, a 5.
I would also strongly recommend not catching exception at all. Almost all functions should not do anything with exceptions. Let it go. Exceptions should only be caught in a very few strategic places in each thread: on the very top, in the main UI cycle, in some special cases. This is not the case. OP should remove exception handling from this method and let exception propagate.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900