try (C++)

From Appmethod Topics
Jump to: navigation, search

Go Up to Keywords, Alphabetical Listing Index


Category

Statements, C++ Specific Keywords

Syntax

try compound-statement handler-list

Description

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.


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