7 Best Practices For Exception Handling In Modern C++
Tags: cpp, tutorial, programming, beginners
Published: 2019-12-02 00:51:59

<!-- wp:paragraph -->
<p>Exception handling in C++ is a well-unschooled topic if you observe initial stages of the learning curve. There are numerous tutorials available online on exception handling in C++ with example. But few explains what you should not do &amp; intricacies around it. So here, we will see some intricacies, from where &amp; why you should not throw an exception along with some newer features introduced in <a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/21-new-features-of-modern-cpp-to-use-in-your-project/" target="_blank"><span style="color:#102eef" class="color">Modern C++</span></a> on exception handling with example. I am not an expert but this is what I have gained from various sources, courses &amp; industry experiences.  </p>
<!-- /wp:paragraph -->

> /!\\\: Originally published @ [www.vishalchovatiya.com](http://www.vishalchovatiya.com/).

<!-- wp:paragraph -->
<p>In the end, we will see the <a href="#Runtime-cost-of-exceptions-with-quick-benchmark"><span style="color:#1704f0" class="color">performance cost of using an exception</span></a> by a quick benchmark code. Finally, we will close the article with <a href="#Best-practices-&amp;-some-CPP-Core-Guidelines-on-exception-handling"><span style="color:#0c24f5" class="color">Best practices&nbsp;&amp; some CPP Core Guidelines on exception handling</span></a>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong><em>Note</em></strong><em>: we will not see anything regarding a dynamic exception as it deprecated from C++11 and removed in C++17. </em></p>
<!-- /wp:paragraph -->


<!-- wp:heading -->
<h2>Terminology/Jargon/Idiom you may face</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li><strong>potentially throwing</strong>: may or may not throw an exception.</li><li><strong>noexcept</strong>: this is specifier as well as operator depending upon where &amp; how you use it. Will see that <a href="#noexcept-specifier-vs-operator"><span style="color:#060af2" class="color">later</span></a>.</li><li><strong><a href="http://www.vishalchovatiya.com/7-advanced-cpp-programming-styles-and-idiom-examples-you-should-know/#RAII" target="_blank" rel="noreferrer noopener" aria-label="RAII (opens in a new tab)"><span style="color:#1c23ee" class="color">RAII</span></a></strong>: <strong>R</strong>esource <strong>A</strong>cquisition <strong>I</strong>s <strong>I</strong>nitialization is a scope-bound resource management mechanism which means resource allocation is done by the constructor &amp; resource deallocation is done by the destructor during the defined scope of the object. I know it's a terrible name but very powerful concept.</li><li><strong><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://stackoverflow.com/questions/11671282/implicitly-declared-special-member-functions" target="_blank"><span style="color:#1c09e8" class="color">Implicitly-declared special member functions</span></a></strong>: I think this need not require any introduction. </li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>1. Implement copy and/or move constructor while throwing user-defined type object </h2>
<!-- /wp:heading -->

```c++
struct demo
{
    demo() = default;
    demo(demo &&) = delete;
    demo(const demo &) = delete;
};

int main()
{
    throw demo{};
    return 0;
}
```
<!-- wp:list -->
<ul><li>Upon throw expression, a copy of the exception object always needs to be created as the original object goes out of the scope during the stack unwinding process.</li><li>During that initialization, we may expect <a rel="noreferrer noopener" href="https://en.wikipedia.org/wiki/Copy_elision" target="_blank"><span style="color:#1410e7" class="color">copy elision</span></a><span style="color:#1410e7" class="color"> </span>(see <a rel="noreferrer noopener" href="https://wg21.cmeerw.net/cwg/issue1493" target="_blank"><span style="color:#0b28e9" class="color">this</span></a>) – omits <a rel="noreferrer noopener" aria-label="copy and move constructors (opens in a new tab)" href="http://www.vishalchovatiya.com/move-constructor-assignment-operator-with-shared-ptr/" target="_blank"><span style="color:#1207f1" class="color">copy or move constructors</span></a> (object constructed directly into the storage of the target object).  </li><li>But even though copy elision may or may not be applied you should provide proper copy constructor and/or move constructor which is what <a aria-label="C++ standard mandates(see point 5 of 15.1) (opens in a new tab)" rel="noreferrer noopener" href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4296.pdf" target="_blank"><span style="color:#0e0af2" class="color">C++ standard mandates(see 15.1)</span></a>. See below compilation error for reference. </li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock {"linenumbers":"false"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">error: call to deleted constructor of 'demo'
    throw demo{};
          ^~~~~~
note: 'demo' has been explicitly marked deleted here
    demo(demo &amp;&amp;) = delete;
    ^
1 error generated.
compiler exit status 1</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>Above error stands true till C++14. Since C++17, If object thrown is a prvalue, the move/copy constructor call is optimized out i.e. <a rel="noreferrer noopener" href="https://en.wikipedia.org/wiki/Copy_elision" target="_blank"><span style="color:#2a17f2" class="color">copy elision</span></a>. </li><li>If we catch an exception by value, we may also expect copy elision(compilers are permitted to do so, but it is not mandatory). The exception object is an lvalue argument when initializing catch clause parameters.  </li></ul>
<!-- /wp:list -->

> TL;DR
class used for throwing the exception object needs copy and/or move constructors


<!-- wp:heading -->
<h2>2. Be cautious while throwing an exception from the constructor </h2>
<!-- /wp:heading -->

```c++
struct base
{
    base(){cout<<"base\n";}
    ~base(){cout<<"~base\n";}
};

struct derive : base
{
    derive(){cout<<"derive\n"; throw -1;}
    ~derive(){cout<<"~derive\n";}
};

int main()
{
    try{
        derive{};
    }
    catch (...){}
    return 0;
}
```

<!-- wp:list -->
<ul><li>When an exception is thrown from a constructor, stack unwinding begins, destructors for the object will be called only &amp; only if an object is created successfully. So be caution with dynamic memory allocation here. In such cases, you should use RAII.</li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock {"linenumbers":"false"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">base
derive
~base</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>As you can see in the above case, the destructor of <code>derive</code> is not executed, Because, it is not created successfully.</li></ul>
<!-- /wp:list -->

```c++
struct base
{
    base() { cout << "base\n"; }
    ~base() { cout << "~base\n"; }
};

struct derive : base
{
    derive() = default;
    derive(int) : derive{}
    {
        cout << "derive\n";
        throw - 1;
    }
    ~derive() { cout << "~derive\n"; }
};

int main()
{
    try{
        derive{0};
    }
    catch (...){}
    return 0;
}
```

<!-- wp:list -->
<ul><li>In the case of constructor delegation, it is considered as the creation of object hence destructor of <code>derive</code> will be called.</li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock {"linenumbers":"false"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">base
derive
~derive
~base</pre>
<!-- /wp:enlighter/codeblock -->

> TL;DR
When an exception is thrown from a constructor, destructors for the object will be called only & only if an object is created successfully </p>

<!-- wp:heading -->
<h2>3. Avoid throwing exceptions out of a destructor</h2>
<!-- /wp:heading -->


```c++
struct demo
{
    ~demo() { throw std::exception{}; }
};

int main()
{
    try{
        demo d;
    }
    catch (const std::exception &){}
    return 0;
}
```

<!-- wp:list -->
<ul><li>Above code seems straight forward but when you run it, it will be terminated as shown below rather than catching the exception. Reason for this is destructors are by default <code>noexcept</code> (i.e. non-throwing) </li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock {"linenumbers":"false"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ clang++-7 -o main main.cpp
warning: '~demo' has a non-throwing exception specification but can still
      throw [-Wexceptions]
    ~demo() { throw std::exception{}; }
              ^
note: destructor has a implicit non-throwing exception specification
    ~demo() { throw std::exception{}; }
    ^
1 warning generated.
$
$ ./main
terminate called after throwing an instance of 'std::exception'
  what():  std::exception
exited, aborted</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li><code>noexcept(false)</code> will solve our problem as below</li></ul>
<!-- /wp:list -->

```c++
struct X
{
    ~X() noexcept(false) { throw std::exception{}; } 
};
```


<!-- wp:list -->
<ul><li>But don’t do it. Destructors are by default non-throwing for a reason, and we must not throw exceptions in destructors unless we catch them inside the destructor.  </li></ul>
<!-- /wp:list -->

<!-- wp:yoast/faq-block {"questions":[{"id":"faq-question-1571466069486","question":["Why you should not throw an exception from a destructor?"],"answer":["Because destructors are called during stack unwinding when an exception is thrown, and we are not allowed to throw another exception while the previous one is not caught – in such a case ",{"type":"code","props":{"children":["std::terminate"]}}," will be called.   "],"jsonQuestion":"Why you should not throw an exception from a destructor?","jsonAnswer":"Because destructors are called during stack unwinding when an exception is thrown, and we are not allowed to throw another exception while the previous one is not caught – in such a case \u003ccode\u003estd::terminate\u003c/code\u003e will be called.   "}]} -->
<div class="schema-faq wp-block-yoast-faq-block"><div class="schema-faq-section"><strong class="schema-faq-question">Why you should not throw an exception from a destructor?</strong> <p class="schema-faq-answer">Because destructors are called during stack unwinding when an exception is thrown, and we are not allowed to throw another exception while the previous one is not caught – in such a case <code>std::terminate</code> will be called.   </p> </div> </div>
<!-- /wp:yoast/faq-block -->

<!-- wp:list -->
<ul><li>Consider the following example for more clarity.</li></ul>
<!-- /wp:list -->

```c++
struct base
{
    ~base() noexcept(false) { throw 1; }
};

struct derive : base
{
    ~derive() noexcept(false) { throw 2; }
};

int main()
{
    try{
        derive d;
    }
    catch (...){ }
    return 0;
}
```
<!-- wp:list -->
<ul><li>An exception will be thrown when the object <code>d</code> will be destroyed as a result of RAII. But at the same time destructor of <code>base</code> will also be called as it is <a rel="noreferrer noopener" aria-label="sub-object (opens in a new tab)" href="http://www.vishalchovatiya.com/memory-layout-of-cpp-object/" target="_blank"><span style="color:#2509f5" class="color">sub-object</span></a> of <code>derive</code> which will again throw an exception. Now we have two exceptions at the same time which is invalid scenario &amp; <code>std::terminate</code> will be called.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>There are some type trait utilities like <code>std::is_nothrow_destructible</code>,  <code>std::is_nothrow_constructible</code>, etc. from <code>#include&lt;type_traits&gt;</code> by which you can check whether the special member functions are exception-safe or not.</p>
<!-- /wp:paragraph -->

```c++
int main()
{
    cout << std::boolalpha << std::is_nothrow_destructible<std::string>::value << endl;
    cout << std::boolalpha << std::is_nothrow_constructible<std::string>::value << endl;
    return 0;
}
```

> TL;DR
1. Destructors are by default&nbsp;<code>noexcept</code>&nbsp;(i.e. non-throwing)
2. You should not throw exception out of destructors because destructors are called during stack unwinding when an exception is thrown, and we are not allowed to throw another exception while the previous one is not caught – in such a case&nbsp;<code>std::terminate</code>&nbsp;will be called.

<!-- wp:heading -->
<h2>4. Rethrowing/Nested exception handling with std::exception_ptr( C++11) example</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>This is more of a demonstration rather the best practice of the nested exception scenario using <code>std::exception_ptr</code>. Although you can simply use <code>std::exception</code> without complicating things much but <code>std::exception_ptr</code> will provide us with the leverage of handling exception out of <code>try</code> / <code>catch</code> clause.</p>
<!-- /wp:paragraph -->

```c++
void print_nested_exception(const std::exception_ptr &eptr=std::current_exception(), size_t level=0)
{
    static auto get_nested = [](auto &e) -> std::exception_ptr {
        try { return dynamic_cast<const std::nested_exception &>(e).nested_ptr(); }
        catch (const std::bad_cast&) { return nullptr; }
    };

    try{
        if (eptr) std::rethrow_exception(eptr);
    }
    catch (const std::exception &e){
        std::cerr << std::string(level, ' ') << "exception: " << e.what() << '\n';
        print_nested_exception(get_nested(e), level + 1);// rewind all nested exception
    }
}
// -----------------------------------------------------------------------------------------------
void func2(){
    try         { throw std::runtime_error("TESTING NESTED EXCEPTION SUCCESS"); }
    catch (...) { std::throw_with_nested(std::runtime_error("func2() failed")); }
}

void func1(){
    try         { func2(); }
    catch (...) { std::throw_with_nested(std::runtime_error("func1() failed")); }
}

int main()
{
    try                             { func1(); }
    catch (const std::exception&)   { print_nested_exception(); }
    return 0;
}
// Will only work with C++14 or above
```
<!-- wp:list -->
<ul><li>Above example looks complicated at first, but once you have implemented nested exception handler(i.e. <code>print_nested_exception</code>). Then you only need to focus on throwing the exception using <code>std::throw_with_nested</code> function. </li></ul>
<!-- /wp:list -->

<!-- wp:enlighter/codeblock {"linenumbers":"false"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">exception: func1() failed
 exception: func2() failed
  exception: TESTING NESTED EXCEPTION SUCCESS</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>The main thing to focus here is <code>print_nested_exception</code> function in which we are rewinding nested exception using <code> std::rethrow_exception</code> &amp; <code>std::exception_ptr</code>.  </li><li><code>std::exception_ptr</code> is a <a rel="noreferrer noopener" aria-label="shared pointer (opens in a new tab)" href="http://www.vishalchovatiya.com/move-constructor-assignment-operator-with-shared-ptr" target="_blank"><span style="color:#2311ea" class="color">shared pointer</span></a> like type though dereferencing it is undefined behaviour. It can hold <a rel="noreferrer noopener" aria-label="nullptr (opens in a new tab)" href="http://www.vishalchovatiya.com/what-exactly-nullptr-is-in-cpp/" target="_blank"><span style="color:#2311ea" class="color">nullptr</span></a> or point to an exception object and can be constructed as:</li></ul>
<!-- /wp:list -->

```c++
std::exception_ptr e1;                                             // null
std::exception_ptr e2 = std::current_exception();                  // null or a current exception
std::exception_ptr e3 = std::make_exception_ptr(std::exception{}); // std::exception
```

<!-- wp:list -->
<ul><li>Once <code>std::exception_ptr</code> is created, we can use it to throw or re-throw exceptions by calling <code>std::rethrow_exception(exception_ptr)</code> as we did above, which throws the pointed exception object.</li></ul>
<!-- /wp:list -->

> TL;DR
1. `std::exception_ptr` extends the lifetime of a pointed exception object beyond a catch clause.
2. We may use `std::exception_ptr` to delay the handling of a current exception and transfer it to some other palaces. Though, practical usecase of `std::exception_ptr` is between threads.

<!-- wp:heading -->
<h2 id="noexcept-specifier-vs-operator">5. Use noexcept specifier vs operator appropriately</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>I think this is an oblivious concept among the other concepts of the C++ exceptions.</li><li><code>noexcept</code> <a href="https://en.cppreference.com/w/cpp/language/noexcept_spec"><span style="color:#0e12fa" class="color">specifier</span></a><span style="color:#0e12fa" class="color"> </span>&amp; <a href="https://en.cppreference.com/w/cpp/language/noexcept"><span style="color:#250af1" class="color">operator</span></a><span style="color:#250af1" class="color"> </span>came in C++11 to replace deprecated(removed from C++17) dynamic exception specification. </li></ul>
<!-- /wp:list -->

```c++
void func() throw(std::exception);                   // dynamic excpetions, removed from C++17

void potentially_throwing();                         // may throw
void non_throwing() noexcept;                        // "specifier" specifying non-throwing function

void print() {}                                  
void (*func_ptr)() noexcept = print;                 // Not OK from C++17, `print()` should be noexcept too, works in C++11/14

void debug_deep() noexcept(false) {}                 // specifier specifying throw
void debug() noexcept(noexcept(debug_deep())) {}     // specifier & operator, will follow exception rule of `debug_deep`

auto l_non_throwing = []() noexcept {};              // Yeah..! lambdas are also in party
```

<!-- wp:heading {"level":3} -->
<h3> noexcept specifier </h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>I think this needs no introduction it does what its name suggests. So let's quickly go through some pointers:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Can be used for normal functions, methods, <a rel="noreferrer noopener" aria-label="lambda functions (opens in a new tab)" href="http://www.vishalchovatiya.com/learn-lambda-function-in-cpp-with-example/" target="_blank"><span style="color:#210eef" class="color">lambda functions</span></a> &amp; function pointer.</li><li>From C++17, function pointer with noexcept can not points to potentially throwing function.</li><li>Finally, don’t use <code>noexcept</code> specifier for <a rel="noreferrer noopener" aria-label="virtual functions (opens in a new tab)" href="http://www.vishalchovatiya.com/part-1-all-about-virtual-keyword-in-cpp-how-virtual-function-works-internally/" target="_blank"><span style="color:#1c0ae8" class="color">virtual functions</span></a> in a base class/interface because it enforces restriction for all overrides. </li><li>Don’t use noexcept unless you really need it. "Specify it when it is useful and correct" - <a rel="noreferrer noopener" aria-label="Google’s cppguide (opens in a new tab)" href="https://google.github.io/styleguide/cppguide.html#noexcept" target="_blank"><span style="color:#1b10ec" class="color">Google’s cppguide</span></a>. </li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>noexcept operator &amp; what is it used for?</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Added in C++11, <code>noexcept</code> operator takes an expression (not necessarily constant) and performs a compile-time check determining if that expression is non-throwing (<code>noexcept</code>) or potentially throwing.</li><li>The result of such compile-time check can be used, for example, to add <code>noexcept</code>specifier to the same category, higher-level function  <code>(noexcept(noexcept(expr)))</code> or in if <code><a rel="noreferrer noopener" aria-label="constexpr (opens in a new tab)" href="http://www.vishalchovatiya.com/when-to-use-const-vs-constexpr-in-cpp/" target="_blank"><span style="color:#1d09f8" class="color">constexpr</span></a></code>.  </li><li>We can use noexcept operator to check if some class has noexcept constructor, noexcept copy constructor, noexcept move constructor, and so on as follows: </li></ul>
<!-- /wp:list -->

```c++
class demo
{
public:
    demo() {}
    demo(const demo &) {}
    demo(demo &&) {}
    void method() {}
};

int main()
{
    cout << std::boolalpha << noexcept(demo()) << endl;                        // C
    cout << std::boolalpha << noexcept(demo(demo())) << endl;                  // CC
    cout << std::boolalpha << noexcept(demo(std::declval<demo>())) << endl;    // MC
    cout << std::boolalpha << noexcept(std::declval<demo>().method()) << endl; // Methods
}
// std::declval<T> returns an rvalue reference to a type
```

<!-- wp:list -->
<ul><li>You must be wondering why &amp; how this information will be useful?<br>This is more useful when you are using library functions inside your function to suggest compiler that your function is throwing or non-throwing depending upon library implementation.</li><li>If you remove constructor, <a rel="noreferrer noopener" aria-label="copy constructor (opens in a new tab)" href="http://www.vishalchovatiya.com/all-about-copy-constructor-in-cpp/" target="_blank"><span style="color:#1c09ee" class="color">copy constructor</span></a> &amp; <a rel="noreferrer noopener" aria-label="move constructor (opens in a new tab)" href="http://www.vishalchovatiya.com/move-constructor-assignment-operator-with-shared-ptr/" target="_blank"><span style="color:#1b07f1" class="color">move constructor</span></a>, it will print <code>true</code> reason being implicitly-declared special member functions are always non-throwing.</li></ul>
<!-- /wp:list -->

> TL;DR
`noexcept` specifier & operator are two different things. `noexcept` operator performs a compile-time check & doesn’t evaluate the expression. While `noexcept` specifier can take only constant expressions that evaluate to either true or false.

<!-- wp:heading -->
<h2>6. Move exception-safe with std::move_if_noexcept </h2>
<!-- /wp:heading -->

```c++
struct demo
{
    demo() = default;
    demo(const demo &) { cout << "Copying\n"; }
    // Exception safe move constructor
    demo(demo &&) noexcept { cout << "Moving\n"; }
private:
    std::vector<int>    m_v;
};

int main()
{
    demo obj1;

    if (noexcept(demo(std::declval<demo>()))){  // if moving safe
        demo obj2(std::move(obj1));             // then move it
    }
    else{
        demo obj2(obj1);                        // otherwise copy it
    }

    demo obj3(std::move_if_noexcept(obj1));     // Alternatively you can do this----------------
    return 0;
}
```

<!-- wp:list -->
<ul><li>We can use <code>noexcept(T(std::declval&lt;T&gt;()))</code> to check if <code>T</code>’s move constructor exists and is <code>noexcept</code> in order to decide if we want to create an instance of <code>T</code> by moving another instance of <code>T</code> (using <code>std::move</code>). </li><li>Alternatively, we can use <code>std::move_if_noexcept</code>, which uses <code>noexcept</code> operator and casts to either <a rel="noreferrer noopener" aria-label="rvalue or lvalue (opens in a new tab)" href="http://www.vishalchovatiya.com/lvalue-rvalue-and-their-references-with-example-in-cpp/" target="_blank"><span style="color:#1410ec" class="color">rvalue or lvalue</span></a>. Such checks are used in <code>std::vector</code> and other containers.</li><li>This will be useful while you are processing critical data which you don't want to lose. For example, we have critical data received from the server that we do not want to lose it at any cost while processing.  In such a case, we should use <code>std::move_if_noexcept</code> which will move ownership of critical data only and only if move constructor is exception-safe.</li></ul>
<!-- /wp:list -->

> TL;DR
Move critical object safely with `std::move_if_noexcept`.

<!-- wp:heading -->
<h2 id="Runtime-cost-of-exceptions-with-quick-benchmark">7. Real cost of exception handling in C++ with benchmark example</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Despite many benefits, most people still do not prefer to use exceptions due to its overhead. So let's clear it out of the way:</p>
<!-- /wp:paragraph -->

```c++
static void without_exception(benchmark::State &state){
    for (auto _ : state){
        std::vector<uint32_t> v(10000);
        for (uint32_t i = 0; i < 10000; i++) v.at(i) = i;        
    }
}
BENCHMARK(without_exception);//----------------------------------------

static void with_exception(benchmark::State &state){
    for (auto _ : state){
        std::vector<uint32_t> v(10000);
        for (uint32_t i = 0; i < 10000; i++){
            try{
                v.at(i) = i;
            }
            catch (const std::out_of_range &oor){}
        }
    }
}
BENCHMARK(with_exception);//--------------------------------------------

static void throwing_exception(benchmark::State &state){
    for (auto _ : state){
        std::vector<uint32_t> v(10000);
        for (uint32_t i = 1; i < 10001; i++){
            try{
                v.at(i) = i;
            }
            catch (const std::out_of_range &oor){}
        }
    }
}
BENCHMARK(throwing_exception);//-----------------------------------------
```



<!-- wp:list -->
<ul><li>As you can see above, <code>with_exception</code> &amp; <code>without_exception</code> has only a single difference i.e. exception syntax. But none of them throws any exceptions. </li><li>While <code>throwing_exception</code> does the same task except it throws an exception of type <code>std::out_of_range</code> in the last iteration.</li><li>As you can see in below bar graph, the last bar is slightly high as compared to the previous two which shows the cost of throwing an exception. </li><li>But the <strong>cost of using exception is zero</strong> here, as the previous two bars are identical. </li><li>I am not considering the optimization here which is the separate case as it trims some of the assembly instructions completely. Also, implementation of compiler &amp; ABI plays a crucial role. But still, it is far better than losing time by setting up a guard(<code>if(error)</code> strategy) and explicitly checking for the presence of error everywhere.</li><li>While in case of exception, the compiler generates a side table that maps any point that may throw an exception (program counter) to the list of handlers. When an exception is thrown, this list is consulted to pick the right handler (if any) and the stack is unwound. See <a rel="noreferrer noopener" aria-label="this (opens in a new tab)" href="https://monoinfinito.wordpress.com/series/exception-handling-in-c/" target="_blank"><span style="color:#050cee" class="color">this</span></a> for in-depth knowledge.</li><li>By the way,  I am using a <a rel="noreferrer noopener" aria-label="quick benchmark (opens in a new tab)" href="http://quick-bench.com/qgpMiwVmHomfDmoLsPkb_i-Qw7M" target="_blank"><span style="color:#2207ec" class="color">quick benchmark</span></a><span style="color:#2207ec" class="color"> </span>&amp; which internally uses  <a rel="noreferrer noopener" aria-label="Google Benchmark (opens in a new tab)" href="https://github.com/google/benchmark" target="_blank"><span style="color:#1703f1" class="color">Google Benchmark</span></a>, if you want to explore more.</li></ul>
<!-- /wp:list -->

<!-- wp:image {"id":1860} -->
<figure class="wp-block-image"><img src="http://www.vishalchovatiya.com/wp-content/uploads/C-exception-bench-mark-without-optimization-1.png" alt="" class="wp-image-1860"/></figure>
<!-- /wp:image -->

<!-- wp:list -->
<ul><li>First and foremost, remember that using <code>try</code> and <code>catch</code> doesn't actually decrease performance unless an exception is thrown.  </li><li>It's "zero cost" exception handling – no instruction related to exception handling is executed until one is thrown. </li><li>But, at the same time, it contributes to the size of executable due to unwinding routines, which may be important to consider for embedded systems. </li></ul>
<!-- /wp:list -->

> TL;DR
No instruction related to exception handling is executed until one is thrown so using `try` / `catch` doesn’t actually decrease performance.

<!-- wp:heading -->
<h2 id="Best-practices-&amp;-some-CPP-Core-Guidelines-on-exception-handling">Best practices &amp; some CPP Core Guidelines on exception handling</h2>
<!-- /wp:heading -->

<!-- wp:yoast/how-to-block {"hasDuration":false,"jsonDescription":"\u003cstrong\u003e Best practices for C++ exception handling \u003c/strong\u003e","steps":[{"id":"how-to-step-1572947455772","name":["Ideally, you should not throw an exception from the destructor, move constructor or ",{"type":"a","props":{"rel":"noreferrer noopener","href":"https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-throwing_swap","target":"_blank","children":[{"type":"span","props":{"style":"color:#0b23f4","class":"color","children":["swap"]}}]}},{"type":"span","props":{"style":"color:#0b23f4","class":"color","children":[" "]}},"like functions.  "],"text":[],"jsonName":"Ideally, you should not throw an exception from the destructor, move constructor or \u003ca rel=\u0022noreferrer noopener\u0022 href=\u0022https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-throwing_swap\u0022 target=\u0022_blank\u0022\u003e\u003cspan style=\u0022color:#0b23f4\u0022 class=\u0022color\u0022\u003eswap\u003c/span\u003e\u003c/a\u003e\u003cspan style=\u0022color:#0b23f4\u0022 class=\u0022color\u0022\u003e \u003c/span\u003elike functions.  ","jsonText":""},{"id":"how-to-step-1572947502208","name":["Prefer RAII idiom for the exception safety because in case of exception you might be left with  "],"text":["- data in an invalid state, i.e. data that cannot be further read \u0026 used;",{"type":"br","props":{"children":[]}},"- leaked resources such as memory, files, ids, or anything else that needs to be allocated and released;",{"type":"br","props":{"children":[]}},"- corrupted memory;",{"type":"br","props":{"children":[]}},"- broken invariants, e.g. size function returns more elements than actually held in a container.    "],"jsonName":"Prefer RAII idiom for the exception safety because in case of exception you might be left with  ","jsonText":"- data in an invalid state, i.e. data that cannot be further read \u0026amp; used;\u003cbr/\u003e- leaked resources such as memory, files, ids, or anything else that needs to be allocated and released;\u003cbr/\u003e- corrupted memory;\u003cbr/\u003e- broken invariants, e.g. size function returns more elements than actually held in a container.    "},{"id":"how-to-step-1572947503168","name":["Avoid using ",{"type":"a","props":{"rel":"noreferrer noopener","href":"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-new","target":"_blank","children":[{"type":"span","props":{"style":"color:#1308f3","class":"color","children":["raw "]}}]}},{"type":"code","props":{"children":[{"type":"a","props":{"rel":"noreferrer noopener","href":"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-new","target":"_blank","children":[{"type":"span","props":{"style":"color:#1308f3","class":"color","children":["new"]}}]}}]}},{"type":"a","props":{"rel":"noreferrer noopener","href":"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-new","target":"_blank","children":[{"type":"span","props":{"style":"color:#1308f3","class":"color","children":[" \u0026 "]}}]}},{"type":"code","props":{"children":[{"type":"a","props":{"rel":"noreferrer noopener","href":"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-new","target":"_blank","children":[{"type":"span","props":{"style":"color:#1308f3","class":"color","children":["delete"]}}]}}]}},". Use solutions from the standard library, e.g. ",{"type":"code","props":{"children":[{"type":"a","props":{"rel":"noreferrer noopener","href":"http://www.vishalchovatiya.com/understanding-unique-ptr-with-example-in-cpp11/","target":"_blank","children":[{"type":"span","props":{"style":"color:#0817f4","class":"color","children":["std::unique_pointer"]}}]}}]}},", ",{"type":"code","props":{"children":["std::make_unique"]}},", ",{"type":"code","props":{"children":["std::fstream"]}},", ",{"type":"code","props":{"children":["std::lock_guard"]}},", etc.  "],"text":[],"jsonName":"Avoid using \u003ca rel=\u0022noreferrer noopener\u0022 href=\u0022https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-new\u0022 target=\u0022_blank\u0022\u003e\u003cspan style=\u0022color:#1308f3\u0022 class=\u0022color\u0022\u003eraw \u003c/span\u003e\u003c/a\u003e\u003ccode\u003e\u003ca rel=\u0022noreferrer noopener\u0022 href=\u0022https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-new\u0022 target=\u0022_blank\u0022\u003e\u003cspan style=\u0022color:#1308f3\u0022 class=\u0022color\u0022\u003enew\u003c/span\u003e\u003c/a\u003e\u003c/code\u003e\u003ca rel=\u0022noreferrer noopener\u0022 href=\u0022https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-new\u0022 target=\u0022_blank\u0022\u003e\u003cspan style=\u0022color:#1308f3\u0022 class=\u0022color\u0022\u003e \u0026amp; \u003c/span\u003e\u003c/a\u003e\u003ccode\u003e\u003ca rel=\u0022noreferrer noopener\u0022 href=\u0022https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-new\u0022 target=\u0022_blank\u0022\u003e\u003cspan style=\u0022color:#1308f3\u0022 class=\u0022color\u0022\u003edelete\u003c/span\u003e\u003c/a\u003e\u003c/code\u003e. Use solutions from the standard library, e.g. \u003ccode\u003e\u003ca rel=\u0022noreferrer noopener\u0022 href=\u0022http://www.vishalchovatiya.com/understanding-unique-ptr-with-example-in-cpp11/\u0022 target=\u0022_blank\u0022\u003e\u003cspan style=\u0022color:#0817f4\u0022 class=\u0022color\u0022\u003estd::unique_pointer\u003c/span\u003e\u003c/a\u003e\u003c/code\u003e, \u003ccode\u003estd::make_unique\u003c/code\u003e, \u003ccode\u003estd::fstream\u003c/code\u003e, \u003ccode\u003estd::lock_guard\u003c/code\u003e, etc.  ","jsonText":""},{"id":"how-to-step-1572947503981","name":["Moreover, it is useful to split your code into modifying and non-modifying parts, where only the non-modifying part can throw exceptions.   "],"text":[],"jsonName":"Moreover, it is useful to split your code into modifying and non-modifying parts, where only the non-modifying part can throw exceptions.   ","jsonText":""},{"id":"how-to-step-1572947504696","name":[" Never throw exceptions while owing some resource.    "],"text":[],"jsonName":" Never throw exceptions while owing some resource.    ","jsonText":""}],"unorderedList":true,"defaultDurationText":"Time needed:"} -->
<div class="schema-how-to wp-block-yoast-how-to-block"><p class="schema-how-to-description"><strong> Best practices for C++ exception handling </strong></p> <ul class="schema-how-to-steps"><li class="schema-how-to-step" id="how-to-step-1572947455772"><strong class="schema-how-to-step-name">Ideally, you should not throw an exception from the destructor, move constructor or <a rel="noreferrer noopener" href="https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-throwing_swap" target="_blank"><span style="color:#0b23f4" class="color">swap</span></a><span style="color:#0b23f4" class="color"> </span>like functions.  </strong> <p class="schema-how-to-step-text"></p> </li><li class="schema-how-to-step" id="how-to-step-1572947502208"><strong class="schema-how-to-step-name">Prefer RAII idiom for the exception safety because in case of exception you might be left with  </strong> <p class="schema-how-to-step-text">- data in an invalid state, i.e. data that cannot be further read &amp; used;<br/>- leaked resources such as memory, files, ids, or anything else that needs to be allocated and released;<br/>- corrupted memory;<br/>- broken invariants, e.g. size function returns more elements than actually held in a container.    </p> </li><li class="schema-how-to-step" id="how-to-step-1572947503168"><strong class="schema-how-to-step-name">Avoid using <a rel="noreferrer noopener" href="https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-new" target="_blank"><span style="color:#1308f3" class="color">raw </span></a><code><a rel="noreferrer noopener" href="https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-new" target="_blank"><span style="color:#1308f3" class="color">new</span></a></code><a rel="noreferrer noopener" href="https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-new" target="_blank"><span style="color:#1308f3" class="color"> &amp; </span></a><code><a rel="noreferrer noopener" href="https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-new" target="_blank"><span style="color:#1308f3" class="color">delete</span></a></code>. Use solutions from the standard library, e.g. <code><a rel="noreferrer noopener" href="http://www.vishalchovatiya.com/understanding-unique-ptr-with-example-in-cpp11/" target="_blank"><span style="color:#0817f4" class="color">std::unique_pointer</span></a></code>, <code>std::make_unique</code>, <code>std::fstream</code>, <code>std::lock_guard</code>, etc.  </strong> <p class="schema-how-to-step-text"></p> </li><li class="schema-how-to-step" id="how-to-step-1572947503981"><strong class="schema-how-to-step-name">Moreover, it is useful to split your code into modifying and non-modifying parts, where only the non-modifying part can throw exceptions.   </strong> <p class="schema-how-to-step-text"></p> </li><li class="schema-how-to-step" id="how-to-step-1572947504696"><strong class="schema-how-to-step-name"> Never throw exceptions while owing some resource.    </strong> <p class="schema-how-to-step-text"></p> </li></ul></div>
<!-- /wp:yoast/how-to-block -->

<!-- wp:paragraph -->
<p><strong>Some CPP Core Guidelines</strong></p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Re-design" target="_blank"><span style="color:#1c08f6" class="color">E.1: Develop an error-handling strategy early in a design</span></a></li><li><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Re-errors" target="_blank"><span style="color:#1c08f6" class="color">E.3: Use exceptions for error handling only</span></a></li><li><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Re-raii" target="_blank"><span style="color:#1c08f6" class="color">E.6: Use RAII to prevent leaks</span></a></li><li><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Re-never-throw" target="_blank"><span style="color:#1c08f6" class="color">E.13: Never throw while being the direct owner of an object</span></a></li><li><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Re-never-fail" target="_blank"><span style="color:#1c08f6" class="color">E.16: Destructors, deallocation, and&nbsp;</span></a><code><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Re-never-fail" target="_blank"><span style="color:#1c08f6" class="color">swap</span></a></code><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Re-never-fail" target="_blank"><span style="color:#1c08f6" class="color">&nbsp;must never fail</span></a></li><li><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Re-not-always" target="_blank"><span style="color:#1c08f6" class="color">E.17: Don’t try to catch every exception in every function</span></a></li><li><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Re-catch" target="_blank"><span style="color:#1c08f6" class="color">E.18: Minimize the use of explicit&nbsp;</span></a><code><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Re-catch" target="_blank"><span style="color:#1c08f6" class="color">try</span></a></code><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Re-catch" target="_blank"><span style="color:#1c08f6" class="color">/</span></a><code><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Re-catch" target="_blank"><span style="color:#1c08f6" class="color">catch</span></a></code></li><li><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Re-no-throw-crash" target="_blank"><span style="color:#1c08f6" class="color">26: If you can’t throw exceptions, consider failing fast</span></a></li><li><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Re_catch" target="_blank"><span style="color:#1c08f6" class="color">E.31: Properly order your&nbsp;</span></a><code><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Re_catch" target="_blank"><span style="color:#1c08f6" class="color">catch</span></a></code><a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Re_catch" target="_blank"><span style="color:#1c08f6" class="color">-clauses</span></a></li></ul>
<!-- /wp:list -->




## You may like these also

- [21 new features of Modern C++ to use in your project](https://dev.to/visheshpatel/21-new-features-of-modern-c-to-use-in-your-project-3f87)
- [All about lambda functions in C++(from C++11 to C++17)](https://dev.to/visheshpatel/all-about-lambda-function-in-c-from-c-11-to-c-17-3p5h)
- [C++ type casting with example for C developers](https://dev.to/visheshpatel/c-type-casting-with-example-for-c-developers-29b8)

[Have any suggestions, query or wants to say `Hi`? Take the Pressure Off, you are just a click away.](http://www.vishalchovatiya.com/contact-2/)🖱️