__finally (C++)

From RAD Studio
Jump to: navigation, search

Go Up to Keywords, Alphabetical Listing Index


Category

Statements, Keyword Extensions

Syntax

__finally {compound-statement}

Description

The __finally keyword specifies actions that should be taken regardless of how the flow within the preceding __try exits.


Example

The following is the code fragment shows how to use the try/__finally construct:

#include <stdio.h>
#include <string.h>
#include <windows.h>

class Exception
{
public:
    Exception(char* s = "Unknown"){what = strdup(s);      }
    Exception(const Exception& e ){what = strdup(e.what); }
    ~Exception()                   {free(what);         }
    char* msg() const             {return what;           }
private:
    char* what;
};

int main()
{
    float e, f, g;
        try
        {
            try
            {
                f = 1.0;
                g = 0.0;
                try
                {
                    puts("Another exception:");
                    e = f / g;
                }
                __except(EXCEPTION_EXECUTE_HANDLER)
                {
                    puts("Caught a C-based exception.");
                    throw(Exception("Hardware error: Divide by 0"));
                }
            }
            catch(const Exception& e)
            {
                printf("Caught C++ Exception: %s :\n", e.msg());
            }
        }
        __finally
        {
            puts("C++ allows __finally too!");
        }
    return e;
}

Running the above program results in the following:

Another exception:
Caught a C-based exception.
Caught C++ exception[Hardware error: Divide by 0]
C++ allows __finally too!

See Also