Tuesday Coding Tip 12 — Stack trace

posted Originally published at medium.com 1 min read

Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.


C++23 brings a new feature that I always wanted since I’ve seen it in C# — stack trace.

When combined with exceptions, it can immensely help with the analysis of user error reports, when you cannot simply attach a debugger. The code snippet shows how to create an exception class that can automatically capture stack trace at the point where it was constructed.

#include <iostream>
#include <stacktrace>
#include <stdexcept>

class stacktrace_error : public std::runtime_error
{
public:
    stacktrace_error(std::stacktrace trace = std::stacktrace::current())
        : std::runtime_error(std::to_string(trace))
    {}
};

void bar() { throw stacktrace_error(); }
void foo() { bar(); }

int main()
{
    try
    {
        foo();
    }
    catch (std::exception& e)
    {
        std::cerr << e.what() << std::endl;
        /* OUTPUTS:
        0> C:\...\Main.cpp(19): Sandbox!bar+0x44
        1> C:\...\Main.cpp(25): Sandbox!foo+0x20
        2> C:\...\Main.cpp(31): Sandbox!main+0x32
        3> D:\a\_work\1\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl(79): Sandbox!invoke_main+0x39
        4> D:\a\_work\1\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl(288): Sandbox!__scrt_common_main_seh+0x12E
        5> D:\a\_work\1\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl(331): Sandbox!__scrt_common_main+0xE
        6> D:\a\_work\1\s\src\vctools\crt\vcstartup\src\startup\exe_main.cpp(17): Sandbox!mainCRTStartup+0xE
        7> KERNEL32!BaseThreadInitThunk+0x14
        8> ntdll!RtlUserThreadStart+0x21
        */
    }
}

The API even allows you to iterate over each stack entry, but honestly — who needs that?

Note: Linux versions of GCC and Clang have this stupid idea of requiring you to manually link stacktrace (akin to math library), because -std=c++23 is apparently not enough of a feature flag. So don't forget to use -lstdc++_libbacktrace argument for compilation.

1 Comment

1 vote

More Posts

Tuesday Coding Tip 06 - Explicit template instantiation

Jakub Neruda - Apr 7

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10

Your Tech Stack Isn’t Your Ceiling. Your Story Is

Karol Modelskiverified - Apr 9

Tuesday Coding Tip 08 — Explicit template specialization

Jakub Neruda - Apr 21

Tuesday Coding Tip 05 - Object initialization in C++

Jakub Neruda - Mar 31
chevron_left

Related Jobs

View all jobs →

Commenters (This Week)

6 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!