John Stirling Stout's Blog

The Try … Catch … Finally … End Try statement

Posted in Uncategorized by johnstirlingstout on June 2, 2009

The Try statement allows you to separate into blocks

  • one or more statements to be executed and that might have an error (these are placed in the Try block)
  • one or more statements to be executed if an error occurs in the Try block (these are placed in the Catch block or blocks)
    • one or more statements to be executed whether or not an error occurs in the Try block and whether or not these are caught (these are placed in the Finally block)

Here is an example, which uses a Try … Catch … End Try statement to try opening a file on a networked drive. If the network connection has failed when file is opened fails the file cannot be read from

        Try
            Dim theFile As New System.IO.StreamReader(“N:\Readme.txt”)
        Catch ex As Exception
            Console.WriteLine(“File not opened. Exception: ” + ex.Message)
        End Try

If the file doesn’t exist the .NET framework raises an exception: somewhat like raising an event: you don’t have to check for the error, just provide a handler for it. The details about the error are placed in an Exception object called ex and the code inside the Catch block can use this information, e.g., by displaying a message.

One problem with this is that an exception can be raised for a number of reasons, not just the File not found error. You can detect the presence or absence of a file with an If statement and using the My.Computer.FileSystem object like this:

        If My.Computer.FileSystem.FileExists(“V:\Readme.txt”) Then
            Try
                Dim theFile As New System.IO.StreamReader(“V:\Readme.txt”)
            Catch ex As Exception
                Console.WriteLine(“File not opened. Exception: ” + ex.Message)
            End Try
        Else
            Console.WriteLine(“File not opened. File or drive does not exist”)
        End If

It is always possible that the file exists when it is tested in the first line, but before the file is opened in the third line it is deleted, so using the Try statement after the initial check for existence is quite a good idea here.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: