catch

From RAD Studio
Jump to: navigation, search

Go Up to Keywords, Alphabetical Listing Index


Category

Statements, C++ Specific Keywords

Syntax

catch (exception_declaration) compound_statement

Description


Used for exception handling techniques, the catch keyword marks an exception handling code block. The specific exception being handled by the said code block is determined by the type of exception given as the exception declaration. The exception declaration can be a pointer to a class derived from the Exception base class, a simple type, a structured type, or the ... notation.

try {
    throw 1;
} catch (int) {
    ShowMessage("int caught");
}

For all the types specified above, except the ... notation, a name for the caught object can be given, in order to be used in the catch code block.

try {
    throw 1;
} catch (int x) {
    ShowMessage("int " + IntToStr(x) + " caught");
}

Any VCL object can be used as an exception and, after the catch code block has finished, the destructor is automatically invoked for the caught object. The following code shows the destructor message.

Each handler will only evaluate an exception that matches - or can be converted to - the type specified in its argument list, except ..., which catches all exceptions.

class MException : public TObject {
    virtual __fastcall ~MException(){ ShowMessage("destructor"); }
};

//somewhere in the code
try {
    throw new MException;
} catch (MException*) {
}

Multiple catch code blocks can be used for the same try. The catch code blocks are being registered by the compiler in the order they are declared. For example:

try {
    throw "exception";
} catch (const char*) {
    ShowMessage("string caught");
} catch (...){
    ShowMessage("anything caught");
}

When multiple catch blocks are being used and a ... block is present, this one must be the last one. The compiler issues an error, but if it did not, the catch code blocks after the ... one would never be called, therefore making them useless.

The catch keyword can only be used in C++ programs; use __try - __except or __try - __finally in C.

See Also