can someone please explain wat try catch and finally is ?

synchro

New member
Joined
Nov 8, 2005
Messages
2
Programming Experience
Beginner
i don't knoew what it is after all my readin
my lecture notes have a lot of material on how to code it, but no reference made to to what it actually does?
thanks in advance
bob
 
They're for exceptions. It's a cleaner way of saying "On Error Goto" in VB6. Instead of having an error be black and white, you can catch errors you think might happen. Then HANDLE them. :)

Try - Everything happens until an exception occurs, then the code is broke at that point and jumps to the corresponding catch.
Catch - Only executes if the exception it's assigned to handle occured in the try section.
Finally - executes whether an exception happens or not.
 
Last edited:
If ever you are unsure what something does, the first place to go is the MSDN online library, assuming you don't have access to a local version.

Just to elaborate a little on sevenhalo's explanation, the Finally block is not always included but is generally used for cleanup code that must be executed whether an exception is thrown or not, like closing a database connection or a file. You may also include more than one Catch block if you want to handle different types of exceptions differently. What many people don't realise is that you can also omit the Catch and just use a Finally to make your code neater. I'm sure many will frown on this example because it has multiple exit points but I actually prefer it that way:
VB.NET:
Private Function DoesFileContainWord(ByVal fileName As String, ByVal word As String) As Boolean
    'Open the file.
    Dim file As New StreamReader(fileName)

    Try
        'Look for the word.
        While file.Peek() <> -1
            If file.ReadLine().IndexOf(word) <> -1
                'The word has been found.
                Return True
            End If
        End While
    Finally
        'Close the file.
        file.Close()
    End Try

    'The word was not found.
    Return False
End Function
Note that the file will be closed even if the Return statement has already been executed, or at least execution has reached that point. This is a very simple example and, as I said, will be frowned on by some, but the principle can be applied to other more complex and more "correct" situations.
 
Back
Top