[dba-VB] C# - but what happened to catch?

Bobby Heid bheid at sc.rr.com
Wed Jul 28 11:10:44 CDT 2010


In the example in John's email, they are going to let the exception "bubble
up".  But they still want to close the reader whether or not there is an
exception.

SO in the example, the try is only so they can have a finally.

Bobby

-----Original Message-----
From: dba-vb-bounces at databaseadvisors.com
[mailto:dba-vb-bounces at databaseadvisors.com] On Behalf Of Shamil
Salakhetdinov
Sent: Saturday, July 24, 2010 1:16 AM
To: 'Discussion concerning Visual Basic and related programming issues.'
Subject: Re: [dba-VB] C# - but what happened to catch?

John,

You can make it like that also:

using (reader = file.OpenText())
	{
         reader.Read(source, 0, length);
      }

Then 'finally' code block will not be needed as reader will be
"automagically" closed by its IDispose call on exit of using code block...

-- Shamil

-----Original Message-----
From: dba-vb-bounces at databaseadvisors.com
[mailto:dba-vb-bounces at databaseadvisors.com] On Behalf Of jwcolby
Sent: Friday, July 23, 2010 11:51 PM
To: VBA
Subject: [dba-VB] C# - but what happened to catch?


http://www.jaggersoft.com/pubs/ExceptionHandlingInCSharp.htm

So they work down through this thing and finally declare "it finally works"
but where is the catch?

I thought the whole point of a try was to do error handling in a catch?




finally?

One way to solve this problem is to guard the call to reader.Close(). A
fourth attempt therefore 
might be:

private static char[] ReadSource(string filename)
{
     TextReader reader = null;
     char[] source;
     try
     {
         FileInfo file = new FileInfo(filename);
         int length = (int)file.Length;
         source = new char[length];
         reader = file.OpenText();
         reader.Read(source, 0, length);
     }
     finally
     {
         if (reader != null)
         {
             reader.Close();
         }
     }
     return source;
}

Of course, the guard on reader.Close() isn't in the "ideal" version of
ReadSource. But this is a 
reasonable version if only because it does, finally, work.

Well.. except that there is no catch.

Sigh!

-- 
John W. Colby
www.ColbyConsulting.com
_______________________________________________
dba-VB mailing list
dba-VB at databaseadvisors.com
http://databaseadvisors.com/mailman/listinfo/dba-vb
http://www.databaseadvisors.com

_______________________________________________
dba-VB mailing list
dba-VB at databaseadvisors.com
http://databaseadvisors.com/mailman/listinfo/dba-vb
http://www.databaseadvisors.com






More information about the dba-VB mailing list