Question Try-Catch Statement advice

Cheetah

Well-known member
Joined
Oct 12, 2006
Messages
232
Programming Experience
Beginner
I am just wondering what the general consensus is for a situation like this:

VB.NET:
        Dim CodeSuccess As Boolean = True

        Try

            If (System.IO.File.Exists("Path_To_File")) Then

                'Do something with the file that file.

            Else

                CodeSuccess = False

            End If

        Catch

            CodeSuccess= False

        End Try

You know that the try catch will catch the error when trying to load the file if it doesn't exist and set the "CodeSuccess" variable to false anyways, but would YOU still put in the File.Exists statement anyways?
 
I would remove the CodeSuccess variable altogether:
VB.NET:
If System.IO.File.Exists("Path_To_File") Then
    Try
        'Do something with the file.
    Catch Ex As Exception

    End Try
End If
 
The CodeSuccess variable is essential, this particular code is contained in a function which returns that boolean, true for if the operation was successful, false if not.
 
Ah, in that case here's how I'd do it:
VB.NET:
    Dim CodeSuccess As Boolean = False
    If System.IO.File.Exists("Path_To_File") Then
        Try
            'Do something with the file.

            CodeSuccess = True
        Catch Ex As Exception

        End Try
    End If
    Return CodeSuccess
End Function
This way it's false unless processing the file works
 
Back
Top