src/
Coverage:
low: ≥ 0%
medium: ≥ 75.0%
high: ≥ 90.0%
Lines:
0 / 7
0.0%
Branches:
-
-%
Functions:
0 / 3
0.0%

utils/exit_request.hpp
Line Branch Exec Source
1 #pragma once
2
3 #include <exception>
4
5 /**
6 * Exception thrown to request that the application exit with a specific code.
7 *
8 * Throwing an ExitRequest signals that the program should shut down in an
9 * orderly way. The exit code travels with the exception, so the top-level
10 * handler can pass it to the operating system. Because the class derives from
11 * std::exception, a catch block for std::exception will also match it, so
12 * handlers that must let it through should catch ExitRequest first.
13 *
14 * Catch it by const reference. The constructor, code(), and what() are all
15 * noexcept, so the object can be created and inspected without risk of
16 * throwing a second exception.
17 */
18 class ExitRequest : public std::exception {
19 private:
20 /** The exit code the application should return to the operating system. */
21 const int exit_code;
22
23 std::string exit_reason{};
24
25 public:
26 /**
27 * Constructs an exit request with the given exit code.
28 *
29 * The constructor is explicit, so an int cannot be implicitly converted to
30 * an ExitRequest. The exit request must be created deliberately.
31 *
32 * @param code The exit code to report when the application terminates.
33 */
34 ✗ explicit ExitRequest(const int code, const std::string& reason = "application exit requested") noexcept
35 ✗ : exit_code(code), exit_reason(reason) {
36 ✗ }
37
38 /**
39 * Returns the exit code carried by this request.
40 *
41 * @return The exit code passed to the constructor. This function does not
42 * throw.
43 */
44 ✗ int code() const noexcept {
45 ✗ return this->exit_code;
46 }
47
48 /**
49 * Returns a description of the exception.
50 *
51 * The message is fixed and does not include the exit code. Use code() to
52 * retrieve the code. The returned pointer refers to a string literal with
53 * static storage duration, so it remains valid for the lifetime of the
54 * program.
55 *
56 * @return A null-terminated string, "application exit requested".
57 */
58 ✗ const char* what() const noexcept override {
59 ✗ return this->exit_reason.c_str();
60 }
61 };
62