Skip to content

Commit 93e65fd

Browse files
committed
add the ability to add an exception handler in the raise function
1 parent 5f90f0e commit 93e65fd

3 files changed

Lines changed: 61 additions & 5 deletions

File tree

include/MGIS/Raise.hxx

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,37 @@
2121

2222
namespace mgis {
2323

24+
//! \brief a simple alias
25+
using ExceptionHandler = void (*)(void);
26+
27+
/*!
28+
* \brief set an exception handler
29+
* \param[in] h: exception handler
30+
*
31+
* \code{.cpp}
32+
* void handler() {
33+
* try {
34+
* throw;
35+
* } catch (std::exception& e) {
36+
* std::cerr << e.what() << '\n';
37+
* } catch (...) {
38+
* std::cerr << "unknown exception thrown";
39+
* }
40+
* std::abort();
41+
* } // end of handler
42+
*
43+
* mgis::setExceptionHandler(handler);
44+
* mgis::raise<std::logic_error>("something went wrong");
45+
* \endcode
46+
*/
47+
MGIS_EXPORT void setExceptionHandler(ExceptionHandler);
48+
49+
/*!
50+
* \brief return a registred exception handler, nullptr if none were
51+
* registred.
52+
*/
53+
MGIS_EXPORT ExceptionHandler getExceptionHandler();
54+
2455
/*!
2556
* \brief a small wrapper used to build the exception outside the
2657
* `throw` statement. As most exception's classes constructors may

include/MGIS/Raise.ixx

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,18 +15,42 @@
1515
#ifndef LIB_MGIS_RAISE_IXX
1616
#define LIB_MGIS_RAISE_IXX
1717

18+
#include <cstdlib>
19+
1820
namespace mgis {
1921

2022
template <typename Exception>
2123
void raise() {
22-
Exception e;
23-
throw(std::move(e));
24+
const auto h = getExceptionHandler();
25+
if (h != nullptr) {
26+
try {
27+
Exception e;
28+
throw(std::move(e));
29+
} catch (...) {
30+
h();
31+
}
32+
std::abort();
33+
} else {
34+
Exception e;
35+
throw(std::move(e));
36+
}
2437
} // end of raise
2538

2639
template <typename Exception, typename... Args>
2740
void raise(Args&&... a) {
28-
Exception e(std::forward<Args...>(a...));
29-
throw(std::move(e));
41+
const auto h = getExceptionHandler();
42+
if (h != nullptr) {
43+
try {
44+
Exception e(std::forward<Args...>(a...));
45+
throw(std::move(e));
46+
} catch (...) {
47+
h();
48+
}
49+
std::abort();
50+
} else {
51+
Exception e(std::forward<Args...>(a...));
52+
throw(std::move(e));
53+
}
3054
} // end of raise
3155

3256
template <typename Exception>

src/CMakeLists.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
mgis_library(MFrontGenericInterface SHARED
2-
ThreadPool.cxx
2+
Raise.cxx
3+
ThreadPool.cxx
34
ThreadedTaskResult.cxx
45
LibrariesManager.cxx
56
Markdown.cxx

0 commit comments

Comments
 (0)