C++ Core Gudelines: goto considered Evil

If you can't throw an exception and can't use final_action (finally) from the guideline support library, you have a problem. Exceptional states require exceptional actions: goto. Really?

 firefighters 1147795 1280

To be honest, I was quite surprised to read in the guidelines about goto exit; as the final rescue. Here are the remaining rules to error handling in the C++ core guidelines.

The first three rules are quite related; therefore, I will write about them together.

E5: If you can’t throw exceptions, simulate RAII for resource management, E.26: If you can’t throw exceptions, consider failing fast, and E.27: If you can’t throw exceptions, use error codes systematically

The idea of RAII is quite simple. If you have to take care of a resource, put the resource into a class. Use the constructor of the class for the initialisation and the destructor for the destruction of the resource. When you create a local instance of the class on the stack, the C++-runtime takes care of the resource and you are done. For more information to RAII, read my previous post Garbage Collection - No Thanks.

What does it mean to simulate RAII for resource management? Imagine, you have a function func which exists with an exception if Gadget can't be created.

void func(zstring arg)
{
    Gadget g {arg};
    // ...
}

 

If you can not throw an exception, you should simulate RAII by adding a valid method to Gadget.

 

error_indicator func(zstring arg)
{
    Gadget g {arg};
    if (!g.valid()) return gadget_construction_error;
    // ...
    return 0;   // zero indicates "good"
}

 

In this case, the caller has to test the return value.

The rules E.26 is straightforward. If there is no way to recover from an error such as memory exhaustion, fail fast. If you can't throw an exception call std::abort which causes an abnormal program termination.

void f(int n)
{
    // ...
    p = static_cast<X*>(malloc(n, X));
    if (!p) abort();     // abort if memory is exhausted
    // ...
}

 

std::abort will only cause an abnormal program termination if you don't install a signal handler which catches the signal SIGABRT.

The function f behaves such as the following function:

void f(int n)
{
    // ...
    p = new X[n];    // throw if memory is exhausted (by default, terminate)
    // ...
}

Now, I will write about the non-word goto in rule E.27.

In case of an error, you have a few issues to solve according to the guidelines:

  1. how do you transmit an error indicator from out of a function?
  2. how do you release all resources from a function before doing an error exit?
  3. What do you use as an error indicator?

In general, your function should have two return values. The value and the error indicator; therefore, std::pair is a good fit. Releasing the resources may easily become a maintenance nightmare, even if you encapsulate the cleanup code in functions.

std::pair<int, error_indicator> user()
{
    Gadget g1 = make_gadget(17);
    if (!g1.valid()) {
            return {0, g1_error};
    }

    Gadget g2 = make_gadget(17);
    if (!g2.valid()) {
            cleanup(g1);
            return {0, g2_error};
    }

    // ...

    if (all_foobar(g1, g2)) {
        cleanup(g1);
        cleanup(g2);
        return {0, foobar_error};
    // ...

    cleanup(g1);
    cleanup(g2);
    return {res, 0};
}

 

Okay, seems to be correct! Or?

Do you know, what DRY stands for? Don't Repeat Yourself. Although the cleanup code is encapsulated into functions the code has a smell of code repetition because the cleanup functions are invoked in various places. How can we get rid of the repetition? Just put the cleanup code at the end of the function and jump to it.

 

std::pair<int, error_indicator> user()
{
    error_indicator err = 0;

    Gadget g1 = make_gadget(17);
    if (!g1.valid()) {
            err = g1_error;          // (1)
            goto exit;
    }

    Gadget g2 = make_gadget(17);
    if (!g2.valid()) {
            err = g2_error;          // (1)
            goto exit;
    }

    if (all_foobar(g1, g2)) {
        err = foobar_error;          // (1)
        goto exit;
    }
    // ...

exit:
  if (g1.valid()) cleanup(g1);
  if (g2.valid()) cleanup(g2);
  return {res, err};
}

 

Admitted, with the help of goto the overall structure of the function is quite clear. In case of an error, just the error indicator (1) is set. Exceptional states require exceptional actions. 

E.30: Don’t use exception specifications

First, here is an example of an exception specification:

int use(int arg)
    throw(X, Y)
{
    // ...
    auto x = f(arg);
    // ...
}

 

This means that the function use may allow throwing an exception of type X, or Y. If a different exception is thrown, std::terminate is called.

Dynamic exception specification with argument throw(X, Y) and without argument throw() is deprecated since C++11. Dynamic exceptions specification with arguments is removed with C++17 but dynamic exception specification without argument will be removed with C++20. throw() is equivalent to noexcept. Here are more details: C++ Core Guidelines: The noexcept Specifier and Operator. 

If you don't know the last rule, it can be very surprising.

E.31: Properly order your catch-clauses

An exception is cached according to the best fit strategy. This means the first exception handler that fits for an actual exception is used. This is the reason you should structure your exception handler from specific to general. If not your specific exception handler may never be invoked. In the following example, the DivisionByZeroException is derived from std::exception.

 

try{
    // throw an exception   (1) 
}
catch(const DivisionByZeroException& ex){ .... } // (2) 
catch(const std::exception& ex{ .... }           // (3) 
catch(...){ .... }                               // (4) 
}

 

In this case, the DivisionByZeroException (2) is used first for handling the exception thrown in line (1). If the specific handler does not work, all exceptions derived from std::exception (3) are caught in the following line. The last exception handler has an ellipsis (4) and can, therefore, catch all exceptions. 

What's next?

As promised, I write in the next post about the five rules for constants and immutability in C++.

 

 

Thanks a lot to my Patreon Supporters: Eric Pederson, Paul Baxter,  Meeting C++, Matt Braun, Avi Lachmish, Roman Postanciuc, Venkata Ramesh Gudpati, and Tobias Zindl.

 

Get your e-book at Leanpub:

The C++ Standard Library

 

Concurrency With Modern C++

 

Get Both as one Bundle

cover   ConcurrencyCoverFrame   bundle
With C++11, C++14, and C++17 we got a lot of new C++ libraries. In addition, the existing ones are greatly improved. The key idea of my book is to give you the necessary information to the current C++ libraries in about 200 pages.  

C++11 is the first C++ standard that deals with concurrency. The story goes on with C++17 and will continue with C++20.

I'll give you a detailed insight in the current and the upcoming concurrency in C++. This insight includes the theory and a lot of practice with more the 100 source files.

 

Get my books "The C++ Standard Library" (including C++17) and "Concurrency with Modern C++" in a bundle.

In sum, you get more than 600 pages full of modern C++ and more than 100 source files presenting concurrency in practice.

 

 Get your interactive course at educative

Modern C++ Concurrency in Practice: Get the most out of any machine

educative

Based on my book "Concurrency with Modern C++" educative.io created an interactive course.

What's Inside?

  • 140 lessons
  • 110 code playgrounds => Run in browser
  • 78 code snippets
  • 55 illustrations

Add comment


Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 1881

All 1174333

Currently are 210 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments