Old School Ways of Handling Status and Error Conditions

C++ provides a number of different ways for returning status and error information from functions. C++17 added a number of new ones or modifications on previously defined ones. This post will look at how you may have done this 15 or more years ago. A second post will continue to this look into handling statuses and error conditions, including the techniques added in C++11, C++14, and C++17.

Let’s say we have a function that takes an input parameter and returns both an output value and a status or error indication. Here are a number of ways of doing this.

Status or Error Code as Function Parameter

Look at the following code:

void foo(int inputParam, int* outputParam, int* status)
{ /* do something */ }

int main()
{
    int in = 1;
    int out;
    int status;
    foo(in, &out, &status);
    if(status == OK) {
        /* use out */
    }
}

In the call to foo, out is valid only if status contains the value OK.

This code is obviously old school. Today, you would more likely use references rather than pointers for the parameters:

void foo(int inputParam, int& outputParam, int& status);

Status or Error Code As Return Value

In the code above, status is returned as a parameter in a subroutine call. Alternatively, and more frequently, the status or error code is set as the return value to a function. For example, foo might be redeclared as:

int foo(int inputParam, int& outputParam);

and used as follows:

int main()
{
    int in = 1;
    int out;
    int status = foo(in, out);
    if (status == OK) {
        /* do something with out value */
    }
}

Special Output Value

If there is a single value that indicates that an operation has failed, but this failure is not necessarily a fatal error condition, a special value may be returned in the output parameter. For example:

int foo(int inputValue)
{
    /* do something, returning valid value, or BadStatus if error condition */
}

int main()
{
    int out = foo(1);
    if ( out != BadStatus ) {
        /* do something with out */
    }
}

This occurs quite frequently, especially in functions that originated in C. A value of NULL might be used as a HANDLE value returned from the Windows libraries to indicate an error occurred. For example, in:

FILE* fp;
fp = fopen("myfile.txt", "r");

fp is NULL if the file myfile.txt does not exist or otherwise cannot be opened for reading.

Similar indicators are used in the Standard Templates Library. For example:

int val {4};
std::vector values {1, 2, 3};
auto iter = std::find(values.begin(), values.end(), val);
if(iter != values.end()) {
    /* iter contains iterator to value found in values vector */
}

In the code above, std::find returns values.end() because 4 is not a value in the values vector.

Return Status and Value in Struct

If a function returns more than one value, a struct containing these multiple values may be defined to contain each of the values. This may be extended to include a status or error code. For example:

struct Ret {
    int status;
    string returnedString;
public:
    Ret() : status(OK) {}
}

Ret foo(int input)
{
    Ret ret{};
    /* do something. Set returnedString if no error.
     * Otherwise, set status to indicate error
     */
    return ret;
}

int main()
{
    Ret returnValue = foo(6);
    if (returnValue.status == OK) {
        // do something with returnValue.returnedString
    }
}

Exceptions

Exceptions may be used to specify that something unexpected has occurred in the execution of the code and that normal processing should not continue. A thrown exception may indicate that the program cannot continue and should therefore be terminated, or that some special processing should be done before continuing.

As an example, let’s say you are creating a C++ library that encapsulates the Vulkan API. You have a Swapchain class that has a method called AcquireNextImage. Within this method, you call vkAcquireNextImageKHR that returns VK_SUCCESS if the call succeeded, VK_ERROR_OUT_OF_DATE_KHR if the drawing surface has changed in some way such as being resized, or any of a number of error statuses. For any of the error statuses, you probably want to inform the program’s user and then terminate the program. For VK_ERROR_OUT_OF_DATE_KHR, you will want to recreate the swap chain to match the new surface properties and then call AcquireNextImage again.

Throwing an exception for any of the error conditions is typical handling, but do you return a status code for the VK_ERROR_OUT_OF_DATE_KHR condition, or do you throw an exception indicating this status? Either would be acceptable, but since this condition happens rarely, I would throw an exception and handle it in the calling code. I think this is slightly cleaner than checking the return status from Swapchain::AcquireNextImage for multiple status values and processing each differently.

That is a rather long-winded description showing how to handle various status and error conditions using exceptions. Here is a simpler case:

void foo()
{
    /* do something */
    throw runtime_error("Error in foo");  // some error occurred
}

int main()
{
    try {
        foo();
    }
    catch (runtime_error& re) {
        /* handle the exception, then either continue after, or terminate */
    }
    // continue processing if non-fatal error occurred
    ...
}

 Review

This post looked into ways that you might return statuses and error codes from a subroutine or function. It also presented exceptions as an alternative. Each of these methods was available prior to C++11 and will certainly show up in legacy code.

The next post will review some of the additional methods that might be used as a result of functionality that was added in C++11, C++14, and C++17.

Advertisements

One thought on “Old School Ways of Handling Status and Error Conditions

  1. Pingback: Modern Ways of Handling Status and Error Conditions | Using C++

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s