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
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
"Renaud Paquay at MC" <r...@miscrit.be> wrote in message
news:3AD8B81B...@miscrit.be...