PSCF v1.1
Exception.cpp
1/*
2* Util Package - C++ Utilities for Scientific Computation
3*
4* Copyright 2010 - 2017, The Regents of the University of Minnesota
5* Distributed under the terms of the GNU General Public License.
6*/
7
8#ifdef UTIL_MPI
9#include <mpi.h>
10#endif
11#include "Exception.h"
12#include "Log.h"
13
14#include <sstream>
15
16namespace Util
17{
18
19 /*
20 * Constructor, with no function name.
21 */
22 Exception::Exception(const char *function, const char *message,
23 const char *file, int line, int echo)
24 : message_()
25 {
26 message_ = " Function: ";
27 message_.append(function);
28 message_.append("\n");
29 message_.append(" Message : ");
30 message_.append(message);
31 message_.append("\n");
32 message_.append(" File : ");
33 message_.append(file);
34 message_.append("\n");
35 message_.append(" Line : ");
36 std::ostringstream s;
37 s << line;
38 message_.append(s.str());
39 message_.append("\n");
40 if (echo) {
42 }
43 }
44
45 /*
46 * Constructor, with no function name.
47 */
48 Exception::Exception(const char *message,
49 const char *file, int line, int echo)
50 : message_()
51 {
52 message_ = " Message : ";
53 message_.append(message);
54 message_.append("\n");
55 message_.append(" File : ");
56 message_.append(file);
57 message_.append("\n");
58 message_.append(" Line : ");
59 std::ostringstream s;
60 s << line;
61 message_.append(s.str());
62 message_.append("\n");
63 if (echo) {
65 }
66 }
67
68 /*
69 * Destructor.
70 */
72 {}
73
74 /*
75 * Write message to stream.
76 */
77 void Exception::write(std::ostream &out)
78 { out << message_ << std::flush; }
79
80 /*
81 * Get message by reference
82 */
83 std::string& Exception::message()
84 { return message_; }
85
86 #ifdef UTIL_MPI
87 /*
88 * Throws exception for code linked to MPI
89 */
91 if (MPI::Is_initialized()) {
92 std::cerr << e.message() << std::endl;
93 Log::file().flush();
94 Log::close();
95 MPI::COMM_WORLD.Abort(65);
96 } else {
97 throw e;
98 }
99 }
100 #endif
101}
A user-defined exception.
Definition: Exception.h:25
std::string & message()
Return the error message.
Definition: Exception.cpp:83
void write(std::ostream &out)
Write error message to output stream.
Definition: Exception.cpp:77
Exception(const char *function, const char *message, const char *file, int line, int echo=1)
Constructor.
Definition: Exception.cpp:22
std::string message_
Error message string.
Definition: Exception.h:80
virtual ~Exception()
Destructor.
Definition: Exception.cpp:71
static void close()
Close log file, if any.
Definition: Log.cpp:45
static std::ostream & file()
Get log ostream by reference.
Definition: Log.cpp:57
Utility classes for scientific computation.
Definition: accumulators.mod:1
void MpiThrow(Exception &e)
Function to throw exception in MPI code.
Definition: Exception.cpp:90