1 /*
2 * Medical Image Registration ToolKit (MIRTK)
3 *
4 * Copyright 2016-2017 Imperial College London
5 * Copyright 2016-2017 Andreas Schuh
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 */
19
20 #ifndef MIRTK_Exception_H
21 #define MIRTK_Exception_H
22
23 #include "mirtk/String.h"
24 #include "mirtk/Stream.h"
25
26
27 namespace mirtk {
28
29
30 /// Enumeration of error types / exit codes
31 enum ErrorType
32 {
33 ERR_None = 0,
34 ERR_Unknown = 1,
35 ERR_LogicError = 2,
36 ERR_InvalidArgument = 3,
37 ERR_RuntimeError = 4,
38 ERR_IOError = 5,
39 ERR_Memory = 6,
40 ERR_NotImplemented = 42
41 };
42
43 /// Convert error type to string
44 template <>
ToString(const ErrorType & value,int w,char c,bool left)45 inline string ToString(const ErrorType &value, int w, char c, bool left)
46 {
47 const char *str;
48 switch (value) {
49 case ERR_None: { str = "NoError"; } break;
50 case ERR_Unknown: { str = "UnknownError"; } break;
51 case ERR_LogicError: { str = "LogicError"; } break;
52 case ERR_InvalidArgument: { str = "InvalidArgument"; } break;
53 case ERR_RuntimeError: { str = "RuntimeError"; } break;
54 case ERR_IOError: { str = "IOError"; } break;
55 case ERR_Memory: { str = "MemoryError"; } break;
56 case ERR_NotImplemented: { str = "NotImplemented"; } break;
57 }
58 return ToString(str, w, c, left);
59 }
60
61 /// Raise error in function
62 ///
63 /// The current implementation prints the error message to STDERR and terminates
64 /// the program with exit code 1. In future releases, when all library code has
65 /// been rewritten to use this function, a suitable runtime exception may be
66 /// thrown instead.
67 ///
68 /// \param[in] err Type of error/exception.
69 /// \param[in] func Name of function which is throwing the error (i.e., __func__).
70 /// \param[in] args Error message. The given arguments are converted to strings
71 /// using the ToString template function. These strings are then
72 /// concatenated to produce the complete error message.
73 template <typename... Args>
Throw(ErrorType err,const char * func,Args...args)74 void Throw(ErrorType err, const char *func, Args... args)
75 {
76 Print(cerr, err, ": ", func, ": ", args...);
77 cerr << endl;
78 exit(static_cast<int>(err));
79 }
80
81
82 } // namespace mirtk
83
84 #endif // MIRTK_Exception_H
85