Loading

Exceptions

try/catch


Example 1

// Basic try/catch block with a handler
try {
    // Some code
    throw 5;
    // Some code
} catch (int iException) {
    // Code to handle exception number 5
}

Example 2

// Basic try/catch for C++ standard exceptions
try {
    // An allocation that might throw a bad_alloc exception
    int* ipArray = new int[iLargeValue];
} catch (std::exception& qrException) {
    // This catches all standard exceptions, including bad_alloc
    // Log the exception using the what() function
    std::cout << qrException.what() << std::endl;
}

Example 3

// A try/catch for all exceptions
try {
    // Some code which might throw various exceptions
} catch(...) {
    // Handler for all exceptions
}

Example 4

// Basic try/catch block with multiple catches
try {
    // Some code that might throw an int or std::exception
} catch (int& irException) {
    // Code to handle integer exceptions
} catch (std::exception& irException) {
    // Code to handle standard exception
}

Example 5

// Basic try/catch block with multiple catches and a catch all
try {
    // Some code that might throw an int or std::exception
} catch (int& irException) {
    // Code to handle integer exceptions
} catch (std::exception& irException) {
    // Code to handle standard exception
} catch (...) {
    // Code to handle anything not caught by previous catches
}

throw


Example 1

// Basic throw
if (bBadCondition) {
    throw 0;
}

Example 2

// Throw an instance of our exception class
if (bBadCondition) {
    throw MyException("Condition Description");
}

Example 3

// Rethrow after a catch
try {
    // Some code which might throw an exception
} catch(...) {
    // Do some initial handling
    // Rethrow the exception for calling functions to handle
    throw;
}

Example 4

// Throwing an uncaught exception
int main() {
    // This thrown exception is not caught. So, unexpected() is called.
    throw 0;
    return 0;
}

Exception Specifications


Example 1

// This function can throw any exception
void MyFunction() {
    // Code which might throw an exception
}

Example 2

// This function can throw int type exceptions only
// All other exceptions cause unexpected() to be called
void MyFunction() throw(int) {
    // Code which might throw an exception
}

Example 3

// This function can throw int or MyException type exceptions only
// All other exceptions cause unexpected() to be called
void MyFunction() throw(int, MyException) {
    // Code which might throw an exception
}

Example 4

// This function cannot throw any exceptions
// Any thrown exceptions cause unexpected() to be called
void MyFunction() throw() {
    // Code which might throw an exception
}