The following code example is taken from the book
C++23 - The Complete Guide
by Nicolai M. Josuttis,
Leanpub, 2026
The code is licensed under a
Creative Commons Attribution 4.0 International License.
// raw code
#include <iostream>
#include <print>
#include <array>
#include <stacktrace>
bool find(const auto& coll, int idx)
{
try {
for (auto i = 0uz; i <= coll.size(); ++i) {
if (coll.at(i) == idx) return true;
}
}
catch (const std::exception&) {
// create stacktrace:
std::stacktrace st = std::stacktrace::current();
// iterate over all entries of the stacktrace:
std::println("DETAILS:");
for (const std::stacktrace_entry& entry : st) {
if (!entry.source_file().empty()) {
std::println(" {}\n at {}, line {}", entry.description(),
entry.source_file(),
entry.source_line());
}
}
}
return false;
}
void callTest()
{
std::array arr{47, 11};
auto arrHas = [&arr] (int i) {
return find(arr, i);
};
std::cout << (arrHas(42) ? "found 42\n" : "no 42\n");
}
int main()
{
callTest();
}