Why use __finally ??

Is there any reason to use _finally in an MFC application?

If so, can some give me a working example?

I don't understand what _finally can do, that you can't do with try-catch
ROWANBRIGHTONAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

AlexFMCommented:
__try - __except block can catch exception which are not handled by C++ try - catch. __finally block adds abitilty to execure cleanup code. The following sample shows how SEH handles error which cannot be catched by C++ try block:

    char* s = NULL;

    int* p = NULL;

    __try
    {
        __try
        {
             s = new char[10];

            *p = 5;
        }
        __except(EXCEPTION_EXECUTE_HANDLER)
        {
            MessageBox(_T("Error"));
        }
    }
    __finally
    {
        if ( s )
            delete[] s;
    }
0
ROWANBRIGHTONAuthor Commented:
A regular C++ try-catch can do the samething.

void test1()
{
    char* s = NULL;
    int* p = NULL;
      try
      {
         s = new char[10];
        *p = 5;
      }
      catch(...)
      {
            printf("test1 got it!\n");
            delete[] s;
      }
}


void test2()
{
    char* s = NULL;
    int* p = NULL;
    __try
    {
        __try
        {
             s = new char[10];
            *p = 5;
        }
        __except(EXCEPTION_EXECUTE_HANDLER)
        {
            printf("test2 got it!\n");
        }
    }
    __finally
    {
        delete[] s;
    }
}
0
ROWANBRIGHTONAuthor Commented:
If a C++ try-catch can peform the same task with cleaner code, why use __finally?

I'm looking to see if there is something __finally can do that a try-catch can not do.
0
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

AlexFMCommented:
About try-catch and __try - __except:

From MSDN topic "try-finally Statement":

Structured exception handling works with Win32 for both C and C++ source files. However, it is not specifically designed for C++. You can ensure that your code is more portable by using C++ exception handling. Also, C++ exception handling is more flexible, in that it can handle exceptions of any type. For C++ programs, it is recommended that you use the new C++ exception-handling mechanism (See try, catch, and throw statements).

From Jeffrey Richter's book "Programming Applications for Microsoft Windows":

One of Microsoft's main motivations for adding SEH to Windows was to ease the development of the operating system itself. The developers of the operating system use SEH to make the system more robust.
Don't confuse structured exception handling with C++ exception handling. C++ exception handling is a different form of exception handling, a form that makes use of the C++ keywords catch and throw. Microsoft's Visual C++ also supports C++ exception handling and is implemented internally by taking advantage of the structured exception handling capabilities already present in the compiler and in Windows operating systems.

Simply talking, C++ programmer doesn't have reason to use SEH.

About __finally: if you want to place cleanup code to separate block, you can use __try-__finally. I don't see advantage here, but semebody may like it. For example, C# has finally block which is responsible for cleanup operations.

BTW, remove line *p = 5 from your test1 function, and you have memory leak.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
AlexFMCommented:
This may be a reason to use __filally block:

void test()
{
    char* s = 0;

    __try
    {
        s = new char[10];
        return;
    }
    __finally
    {
        if ( s )
            delete[] s;
    }
}

Notice that  __finally block is executed in any case, even if there is return statement inside of __try block.
0
AlexFMCommented:
__finally is C way to make cleanup operations. C++ way is using smart pointers.
0
jkrCommented:
You don't have to use '__finally' with exceptions. It is a quite useful byproduct of SEH when combined with '__leave', e.g.

DWORD dwRC;

    __try
    {
        ProgramInit (   pwszFile);

        dwRC    =   Test1();

        if  (   dwRC)   __leave;

        dwRC    =   Test2();

        if  (   dwRC)   __leave;

        dwRC    =   Test3();
    }
    __finally
    {
        ProgramTerm ();
    }

>> __finally is C way to make cleanup operations

No, it is the SEH way - regardless of the language used.
0
rdrunnerCommented:
Hello

Like the other posters already mentioned you should place all cleanup operations in the finally block. This will ensure that the objectes are disposed properly. This is expecially importent if you use "expensive" object like database connections or thelike. The finally block makes sure that this section will be executed and will allow the cleanup to take place regardeless what happend before this. Its like designating a small section of code as "has to be run"
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
System Programming

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.