-
Notifications
You must be signed in to change notification settings - Fork 0
Error Class
The Error
class is used for creating custom error messages with line number and file name information in C++ programs.
The preprocessor definition Exception(message)
is defined as Error(message, __LINE__, __FILE__)
, which creates an instance of the Error
class with the provided message, line number, and file name (the line number and file name are from where the Exception(message)
was called).
#define Exception(message) Error(message, __LINE__, __FILE__)
The Error
class is defined with two constructors and a public member function.
The first constructor takes in a const std::string&
parameter for the message and initializes the private message_
member variable with the provided message.
Error::Error(const std::string &message) : message_(message) {}
The second constructor takes in a const std::string&
parameter for the message, an int
parameter for the line number, and a const char*
parameter for the file name. It creates the message by concatenating the provided message, the line number, and the file name, and then initializes the private message_ member variable with the concatenated string.
Error::Error(const std::string &message, int line, const char *file)
{
message_ = message + "\nexception at line " + std::to_string(line) + ", " + file;
}
The message()
function is a public member function that returns the private message_ member variable as a string.
std::string Error::message() const
{
return message_;
}
The following code snippet creates an instance of the Error class and throws an exception:
#include "assertion.hpp"
int main()
{
try
{
throw(Exception("An error occurred"));
}
catch (const Error& e)
{
std::cerr << e.message() << std::endl;
}
return 0;
}
The try
block throws an exception using the Exception
preprocessor definition. The catch
block catches the exception as a const Error&
reference and calls the message()
function to retrieve the error message.
The terminal should display the following:
An error occurred
exception at line 7, src/Debug.cpp