try (C++)

From RAD Studio
Jump to: navigation, search

Go Up to Keywords, Alphabetical Listing Index


Statements, C++ Specific Keywords


try compound-statement handler-list


The try keyword is supported only in C++ programs. Use __try in C programs. C++ also allows __try.

A block of code in which an exception can occur must be prefixed by the keyword try. Following the try keyword is a block of code enclosed by braces. This indicates that the program is prepared to test for the existence of exceptions. If an exception occurs, the program flow is interrupted. The sequence of steps taken is as follows:

  • The program searches for a matching handler
  • If a handler is found, the stack is unwound to that point
  • Program control is tranferred to the handler

If no handler is found, the program will call the terminate function. If no exceptions are thrown, the program executes in the normal fashion.


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
    Exception(char* s = "Unknown"){what = strdup(s);      }
    Exception(const Exception& e ){what = strdup(e.what); }
    ~Exception()                   {free(what);         }
    char* msg() const             {return what;           }
    char* what;

int main()
    float e, f, g;
            f = 1.0;
            g = 0.0;
                puts("Another exception:");
                e = f / g;
                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());
        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