• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 482
  • Last Modified:

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
0
ROWANBRIGHTON
Asked:
ROWANBRIGHTON
2 Solutions
 
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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
 
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

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now