Example: core_exceptions_example

Examples of use for MRPT exceptions macros.

Console output:

==== MRPT exception ====
Message:  Aw!
Call stack backtrace:
[0 ] /home/jlblanco/code/mrpt/samples/core_exceptions_example/test.cpp:21 test_except_3rd_lvl()
[1 ] /home/jlblanco/code/mrpt/samples/core_exceptions_example/test.cpp:28 test_except_2nd_lvl()
[2 ] /home/jlblanco/code/mrpt/samples/core_exceptions_example/test.cpp:35 test_except_toplevel()
[3 ] /home/jlblanco/code/mrpt/samples/core_exceptions_example/test.cpp:54 main
[4 ] (unknown file) __libc_start_main
[5 ] (unknown file) _start
==== MRPT exception ====
vector::_M_range_check: __n (which is 10) >= this->size() (which is 2)
Call stack backtrace:
[0 ] /home/jlblanco/code/mrpt/samples/core_exceptions_example/test.cpp:45 test_except_2nd_lvl_bis()
[1 ] /home/jlblanco/code/mrpt/samples/core_exceptions_example/test.cpp:48 test_except_toplevel_bis()
[2 ] (unknown file) __libc_start_main
[3 ] (unknown file) _start

C++ example source code:

/* +------------------------------------------------------------------------+
   |                     Mobile Robot Programming Toolkit (MRPT)            |
   |                          https://www.mrpt.org/                         |
   |                                                                        |
   | Copyright (c) 2005-2024, Individual contributors, see AUTHORS file     |
   | See: https://www.mrpt.org/Authors - All rights reserved.               |
   | Released under BSD License. See: https://www.mrpt.org/License          |
   +------------------------------------------------------------------------+ */


#include <mrpt/core/exceptions.h>

#include <iostream>

void test_except_3rd_lvl()
{
    MRPT_START
    THROW_EXCEPTION("Aw!");
    MRPT_END
}

void test_except_2nd_lvl()
{
    MRPT_START
    test_except_3rd_lvl();
    MRPT_END
}

void test_except_toplevel()
{
    MRPT_START
    test_except_2nd_lvl();
    MRPT_END
}

void test_except_2nd_lvl_bis()
{
    MRPT_START
    std::vector<int> x;
    x.resize(2);
    x.at(10);  // throws
    MRPT_END
}

void test_except_toplevel_bis() { test_except_2nd_lvl_bis(); }

int main()
{
    try
    {
        test_except_toplevel();
        return 0;
    }
    catch (const std::exception& e)
    {
        std::cerr << e.what();
    }

    try
    {
        test_except_toplevel_bis();
        return 0;
    }
    catch (const std::exception& e)
    {
        std::cerr << e.what();
    }

    return 0;
}