1 // Copyright (c) 2018 Intel Corporation
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
16 * @brief A header file for the user input exception
17 * \file user_exception.hpp
28 * @def THROW_USER_EXCEPTION
29 * @brief A macro used to throw the exception with a notable description
31 #define THROW_USER_EXCEPTION(exitCode) \
32 throw UserException(exitCode)
35 * @class UserException
36 * @brief The UserException class implements an exception appearing as a result of user input
38 class UserException : public std::exception {
39 mutable std::string errorDesc;
40 std::shared_ptr<std::stringstream> exception_stream;
45 * @brief A C++ std::exception API member
46 * @return An exception description with a file name and file line
48 const char *what() const noexcept override {
49 if (errorDesc.empty() && exception_stream) {
50 errorDesc = exception_stream->str();
52 return errorDesc.c_str();
56 * @brief A constructor. Creates a UserException object
58 explicit UserException(int exitCode) : _exitCode(exitCode) {
61 UserException(int exitCode, std::string msg) : _exitCode(exitCode) {
66 * @brief A stream output operator to be used within exception
67 * @param arg Object for serialization in the exception message
70 UserException &operator<<(const T &arg) {
71 if (!exception_stream) {
72 exception_stream.reset(new std::stringstream());
74 (*exception_stream) << arg;
78 int exitCode() const { return _exitCode; }
81 class UserExceptions : public std::exception {
82 std::list<UserException> _list;
83 mutable std::string msg;
86 UserExceptions &operator<<(const UserException &arg) {
91 const char *what() const noexcept override {
94 if (_list.size() == 1) {
95 ss << _list.back().what();
97 auto iter = _list.begin();
98 for (int i = 0; i < _list.size() - 1; i++) {
99 ss << "\t* " << (*iter++).what() << std::endl;
101 ss << "\t* " << _list.back().what();
108 const std::list<UserException>& list() const {
112 bool empty() const { return _list.empty(); }