Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Nesting structured exception handling ?

1 view
Skip to first unread message

Ike van den Heiligenberg

unread,
Apr 13, 2001, 11:01:44 AM4/13/01
to
In C/C++ a lot of functions return some kind of null-value or
invalid_handle_value, instead of raising an exception. As I understand it
the .Net approach is to always raise exceptions, and catch them with a
try/catch block.

Consider the following pseudo-code-snippet, a function which opens three
files and does some stuff with them:

HANDLE hFile1, hFile2, hFile3

hFile1 = OpenFile(file1)
if(hFile1 != INVALID_HANDLE_VALUE)
{
hFile2 = OpenFile(file2)
if(hFile2 != INVALID_HANDLE_VALUE)
{
hFile3 = OpenFile(file3)
if(hFile3 != INVALID_HANDLE_VALUE)
{
// Do stuff...

CloseHandle(hFile3)
}
CloseHandle(hFile2)
}
CloseHandle(hFile1)
}

This code might not be particularly elegant, but if something goes wrong,
everything will be cleaned up perfectly. It doesn't matter which OpenFile
fails, all open handles at that point will be closed.

How would one do something like this in C# with methods that don't return
invalid values, but raise exceptions instead. Would one nest three
try/catch/finalize blocks?? The important part offcourse is that open
handles must be closed and not-opened handles must not be closed.

Ike van den Heiligenberg

Renaud Paquay at MC

unread,
Apr 14, 2001, 4:50:35 PM4/14/01
to

Yes, you would use 3 nested try/finally blocks:

File File1 = OpenFile(file1)
try
{
File File2 = OpenFile(file2)
try
{
File File3 = OpenFile(file3)
try
{
// Do stuff...

}
finally
{
File3.Close();
}
}
finally
{
File2.Close();
}
finally
{
File1.Close();
}

Note that, in my opinion, it is better not to declare File1,2,3
before the 3 blocks, but to declare them as late as possible,
to avoid potential re-use of a closed file.

Note I've heard that C# beta2 will offer some sort of deterministic
destruction, so that try/finally blocks will be generated behind
the scene by the compiler.

Renaud

Eric Gunnerson (MSFT)

unread,
Apr 16, 2001, 12:31:52 PM4/16/01
to
For objects that implement IDisposable, Beta2 provides a using statement to
do the same thing, but in a nicer way.

"Renaud Paquay at MC" <r...@miscrit.be> wrote in message
news:3AD8B81B...@miscrit.be...

0 new messages