Introduce boost::exception to me - c++

I am asked to create "customizable exception framework" using boost::exception. Till date I used only simple exceptions defined by me. So std::exception,boost::exception are new to me. The code is below.
#include <iterator>
#include<string>
#include <algorithm>
#include<errno.h>
struct My_exception:public virtual boost::exception
{
};
int main()
{
std::string fileName="tmp.txt";
std::string mode="r";
try
{
if(fopen(fileName.c_str(),mode.c_str()))
std::cout << " file opened " << std::endl ;
else
{
My_exception e;
e << boost::errinfo_api_function("fopen") << boost::errinfo_file_name(fileName)
<< boost::errinfo_file_open_mode(mode) << boost::errinfo_errno(errno);
throw e;
}
}
catch(My_exception e)
{
// extract the details here //
}
return 1;
}
Now, I want to know that how to extract the data from that caught exception. Can anybody guide me in the path of boost::exception

First of all, your code has error, for example you cannot write this:
e << boost::errinfo_api_function("fopen")
Because errinfo_api_function can be used with int only. So do something like this:
e << boost::errinfo_api_function(100) //say 100 is error code for api error
See the second type parameter to errinfo_api_function1, it's int. Similarly, check other error class templates. I've given the link to each of them you're using, at the end of this post!
1. It seems there're two version of this class template, one which takes int, other which takes const char*. Compare version 1.40.0 errinfo_api_function with version 1.45.0 errinfo_api_function. Thanks to dalle who pointed it out in the comment. :-)
Use get_error_info function template to get data from boost::exception.
See what boost::exception documentation says,
To retrieve data from a
boost::exception object, use the
get_error_info function template.
Sample code:
//since second type of errinfo_file_name is std::string
std::string fileError = get_error_info<errinfo_file_name>(e);
//since second type of errinfo_errno is int
int errno = get_error_info<errinfo_errno>(e);
//since second type of errinfo_file_open_mode is std::string
std::string mode = get_error_info<errinfo_file_open_mode>(e);
//since second type of errinfo_api_function is int
int apiError = get_error_info<errinfo_api_function>(e);
See these for better understanding:
errinfo_file_name
errinfo_errno
errinfo_file_open_mode
errinfo_api_function

Related

Why does my class std::vector member always throw a segfault?

I've searched endlessly on SE for a logical explanation for why this is happening. It is probably something very simple that I've overlooked, however I cannot spot it and would really appreciate some assistance with this.
Last week I implemented a class to read the output of a system call from a .ini file and then find and store the required information into custom objects that are then stored in a vector inside a Config class. It is a Singleton config class storing a unique_ptr for each instance of my custom class that is created.
The thing is, when I implemented this last week on my laptop, I had zero issues reading and writing to my member vector and was able to get it working exactly how I needed it. Since pulling to my desktop computer, this vector, and any STL container that I use as a member of my class, throws a segmentation fault when I try to do anything on it, even get it's size.
I've tried to shorten the code below to only include sections that actually use this vector. I have replaced my config with A, and custom class with T, and no matter where I try to use my member container, or any other test STL containers that I add to the class, I get a segfault.
For the record, I am using Qt with C++11.
Update: This example breaks on line 50 of c.cpp when debugging, and anywhere that tries to call the vector.
Debug points to this line in stl_vector.h
// [23.2.4.2] capacity
/** Returns the number of elements in the %vector. */
size_type
size() const _GLIBCXX_NOEXCEPT
/*-> this line */ { return size_type(this->_M_impl._M_finish - this->_M_impl._M_start); }
main.cpp
#include "c.h"
int main(int argc, char *argv[])
{
C *c = C::getInstance();
delete c;
return 0;
}
t.h - Class stores information from file
#include <string>
class T
{
public:
T();
bool Active();
std::string getA();
void setA(std::string);
private:
std::string a;
};
t.cpp
#include "t.h"
T::T()
{
}
bool T::Active()
{
if(a == "")
{
return false;
}
return true;
}
std::string T::getA()
{
return this->a;
}
void T::setA(std::string newa)
{
this->a = newa;
}
c.h - Class stores T objects and parses file for information
#include "t.h"
#include <QDebug>
#include <vector>
#include <algorithm>
#include <iostream>
#include <memory>
#include <sstream>
#include <fstream>
class C
{
public:
static C* getInstance();
private:
C();
static C* instance;
static bool init;
std::vector<std::unique_ptr<T>> t_list;
void readLines(const std::string&);
};
c.cpp
#include "c.h"
bool C::init = false;
C* C::instance = nullptr;
C::C()
{
system("echo this is a test command > a.ini");
instance->readLines("a.ini");
}
C* C::getInstance()
{
if(!init)
{
instance = new C;
init = true;
}
return instance;
}
void C::readLines(const std::string &path)
{
T* new_t;
std::ifstream file(path.c_str());
if(!file.is_open())
{
qDebug() << "Unable to open " << path.c_str();
}
std::ofstream o("test.txt");
std::string line;
while(std::getline(file, line))
{
// Split string before searching
std::stringstream ss(line);
std::string seg;
std::vector<std::string> split;
std::string left, right;
// Search patterns
size_t find_a = line.find("a");
size_t del = line.find(':');
if(find_a != std::string::npos)
{
o << "test_Size: " << t_list.size() << std::endl;
if(new_t->Active())
{
T* temp = new_t;
std::unique_ptr<T> move_t(temp);
t_list.push_back(std::move(move_t));
}
o << "test: " << t_list.size() << std::endl;
std::string n;
// Check if previous ahas any null elements
// Split string to find a
n = line.substr(line.find("a "));
n = n.substr(n.find(" ", +2));
new_t->setA(n);
}
else
{
continue;
}
}
// Add last a
T* t = new_t;
std::unique_ptr<T> move_t(t);
//t_list.push_back(std::move(move_t));
o << "a: " << t_list.back().get()->getA() << std::endl;
o << t_list.size() << std::endl;
o.close();
file.close();
}
UPDATE after code change:
I see two things now: One is that new_t in C::readlines is never initialized, so this could break when new_t->Active() is called a bit later in the function. However, I believe that the main problem you're running into is in C::C(), where it says
instance->readLines("a.ini");
At this point in the execution, C::instance is not yet initialized -- you're only just constructing the object that would later be assigned to it. Because of this, this in the readlines call is invalid, and any attempt to access object members will cause UB. This latter problem can be fixed by just calling
readLines("a.ini");
in which case the currently constructed object (that will later be instance) is used for this. I have no idea what you want to happen for the first, though, so all I can say is: If you want to have a vector<unique_ptr<T>>, you will have to create objects of type T with either new T() or (arguably preferrably) std::make_unique<T>() and put them in there.
I'll also say that this is a rather ugly way to implement a singleton in C++. I mean, singletons are never really pretty, but if you're going to do it in C++, the usual way is something like the accepted answer of C++ Singleton design pattern .
Old answer:
The problem (if it is the only one, which I cannot verify because you didn't provide an MCVE) is in the lines
T move_t = new_T;
std::unique_ptr<Adapter> ptr_t(&move_t); // <-- particularly this one
m_ts.push_back(std::move(ptr_t));
You're passing a pointer to a local object into a std::unique_ptr, but the whole purpose of std::unique_ptr is to handle objects allocated with new to avoid memory leaks. Not only will the pointer you pass into it be invalid once the scope surrounding this declaration is left, even if that weren't the case the unique_ptr would attempt to delete an object that's not on the heap at the end of its lifecycle. Both problems cause undefined behavior.
To me, it looks as though you really want to use a std::vector<T> instead of std::vector<std::unique_ptr<T>>, but that's a design issue you'll have to answer yourself.
Answering my own question here. I am trying to call a member variable from within the constructor of the object that holds it, so the vector I am trying to access is not yet instantiated and doesn't exist in memory. That is what causes the Segmentation fault to occur, I am trying to access memory that is not allocated yet, hence any call acting on any member of my C class was causing this issue.
I fixed this problem by adding a public function to the class that then calls the private readLines() function. I call that public function from the object that will take ownership of it, and since this occurs after it has been instantiated, the memory is accessible and the problem disappears.

pass class variable to exception in C++

This is a (modified) problem from a test last week.
I was given an exception class with a predefined number in it:
class ErrorException {
/**
* Stub class.
*/
private :static long ErrorCode;
public: ErrorException( string str) {
cout <<str;
}
};
long ErrorException::ErrorCode = -444;
I think I was supposed to do was catch the exception and then return the number as an error code, but I could not figure out how to get the number in. I could make the catch return a string but not the number as string:
#include "stdafx.h"
#include <iostream>
#include "ErrorException.h"
#include "errno.h""
#include <string>;
class FillerFunction {
public :
virtual int getFillerFunction(int x) throw (ErrorException) = 0;
} // this notation means getFillerFunction is always throwing ErrorException?
double calculateNumber(int y){
//.....
try{
if (y !=0){
throw(ErrorException(?????))
}
};
double catchError(){
catch(ErrorException& x);
};
I eventually made it return the string "error" which is no better than using an if statement. I've looked up other catch-throw examples in c++ and dynamic exceptions, but I can't find an example with an exception grabbing a variable defined in the class.How do I access the ErrorCode, save changing the return type of ErrorException()?
Though this question has already been answered, I just want to add a few notes on proper exception handling in C++11:
First, throw(ErrorException) should not be used, as it is deprecated: http://en.cppreference.com/w/cpp/language/except_spec
Also, it is generally advisable to make use of the fact that C++ provides standard exception classes, personally I usually derive from std::runtime_error.
In order to really take advantage of the exception mechanism in C++11, I recommend using std::nested_exception and std::throw_with_nested as described on StackOverflow here and here. Creating a proper exception handler will allow you to get a backtrace on your exceptions inside your code without need for a debugger or cumbersome logging. Since you can do this with your derived exception class, you can add a lot of information to such a backtrace!
You may also take a look at my MWE on GitHub, where a backtrace would look something like this:
Library API: Exception caught in function 'api_function'
Backtrace:
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"
In your throw you're constructing an exception object. If you prefer to pass a number, you must provide the appropriate constructor.
Quick and dirty:
class ErrorException {
private :
static long ErrorCode;
public:
ErrorException( string str) {
cerr <<str<<endl;
}
ErrorException( long mynumeric code) {
cerr <<"error "<<mynumericcode<<endl;
}
};
The catching should look like:
double calculateNumber(int y){
try {
if (y !=0){
throw(ErrorException(227));
}
} catch(ErrorException& x) {
cout << "Error catched"<<endl;
}
}
Must be elaborated further
It's unusual to to print something in the exception constructor. You'd better populate the information needed in the catch, so that these information could later be accessed with the appropriate getter. The printing would then occur in the exception handler.
If you have a static error code, I suppose that somewhere you have a function that returns the last error code whatever happened. So maybe you'd update this code (but how do you intend to update it with the existing string alternative ?
Here how it could look like:
class ErrorException {
private :
static long LastErrorCode;
long ErrorCode;
string ErrorMessage;
public:
ErrorException(long ec, string str) : ErrorCode(ec), ErrorMessage(str)
{
LastErrorCode = ec;
}
static long getLastError() const { return LastErrorCode; } // would never be reset
long getError() const { return ErrorCode; }
string getMessage() const { return ErrorMessage; }
};
The catching should look like:
double calculateNumber(int y){
try {
if (y !=0){
throw(ErrorException(227,"y is not 0"));
}
} catch(ErrorException& x) {
cerr << "Error "<<x.getError()<<" : "<<x.getMesssage()<<endl;
}
cout << "Last error ever generated, if any: " << ErrorException::getLastErrror()<<endl;
}
Neverthesess, I'd advise you to have a look at std::exception before reinventing the wheel.

What's the grammar meaning of '&buf_pool->watch[0]'?

I read code in buf0buf.cc of mysql's innodb buffer source code here:
link from git hub
And I got this:
&buf_pool->watch[0]
What is the value of the statement? address? or another value?
What does the code mean?(grammar meaning)
Due to operator precedence, this expression is parsed like:
&( (buf_pool->watch)[0] )
In English, the value is the address of the first element of the watch member container in buf_pool.
You can find out.
First of all, let's take the buf_bool variable and look for its declaration. As you can see a few lines above, it's a function parameter:
const buf_pool_t* buf_pool
This means we have to find the definition of the buf_pool_t type. With a mere full-text search, the type definition is not revealed. However, googling for "mysql buf_pool_t" gets us to http://www.iskm.org/mysql56/structbuf__pool__t.html, which in turn tells us that the type is defined in a file called buf0buf.h. That one's also included in the source file you've linked to:
#include "buf0buf.h"
It does indeed contain the definition we are looking for, and that definition includes a member called watch:
struct buf_pool_t{
(...)
buf_page_t* watch;
(...)
};
watch is a pointer to buf_page_t.
So if we go back to the statement in your question:
&buf_pool->watch[0]
watch is interpreted as a pointer to the first element of a buf_page_t array, watch[0] is the first element itself, and the address-of operator yields a pointer to that first element.
So the whole statement reads as:
a pointer to the first element of a buf_page_t array.
Curiously, &buf_pool->watch[0] is equal to buf_pool->watch. Here is a simple (C++11) toy program to verify all of this:
#include <iostream>
#include <typeinfo>
using buf_page_t = int;
struct buf_pool_t {
buf_page_t* watch;
};
int main()
{
const buf_pool_t example = { new buf_page_t[1] };
const buf_pool_t* buf_pool = &example;
std::cout << typeid(&buf_pool->watch[0]).name() << "\n";
std::cout << typeid(buf_pool->watch).name() << "\n";
std::cout << (&buf_pool->watch[0] == buf_pool->watch) << "\n"; // prints 1
}
&buf_pool->watch[0] is the the address of the member 0 of watch contained in the struct buf_bool. Which is watch itself.
It is parsed like that because the whole buf_pool->watch[0] gets under the & (address of) sign.
You can check with this snippet:
#include <iostream>
#include <stdio.h>
using namespace std;
struct hello_t
{
int before;
int array[5];
};
int main() {
// your code goes here
struct hello_t hello;
hello.array[0] = 100;
struct hello_t* ptr_hello;
ptr_hello = &hello;
printf("ptr_hello = %X\n", ptr_hello);
printf("&ptr_hello = %X\n", &ptr_hello);
printf("&ptr_hello->before = %X\n", &ptr_hello->before);
printf("&ptr_hello->array[0] = %X\n", &ptr_hello->array[0]);
printf("");
return 0;
}
https://ideone.com/fwDnoz

how does the structure dereference operator work?

I am a java programmer trying to teach myself c++. Please cut me a little slack if I ask simple questions at first.
I would like to understand how the structure dereference operator works. Specifically, can anyone tell me what the following line of code does in explicit terms?
if (elements[i]->test(arga, argb)) {}
test(arga,argb) is a Boolean function in the same class, and elements is a vector of instances of the element class. Here is the code that immediately surrounds the line above, about which I am interested:
for (unsigned i = 0; i < elements.size(); ++i) {
T arga = INFINITY, argb = INFINITY;
//using namespace std;
//std::cout >> elements[i] >> std::endl;
//std::cout >> test(arga, argb) >> std::endl;
if (elements[i]->test(arga, argb)) {
//some code
}
}
It seems that the if line is testing to see whether or not the boolean returned by test(arga,argb) is part of the given instance of the elements class. But when I try to expose the underlying values of elements[i] or test(arga,argb) with the cout lines above, the compiler throws errors until I comment those lines out. In java, I would be able to fiddle around with this until I found values of each that correspond with each other, and then I would understand the line of code. But I do not know how to figure out what this line of code does in C++. Can anyone give me a clear explanation, preferably supported by a link or two to some references online?
elements[i]->test (arga, argb)
If we break down the statement, reading from left-to-right, we will end up with the below:
access the ith element in an array (or array-like) entity named elements
the element accessed (elements[i]) is a pointer to an object
call the member-function named test on elements[i] and pass it two arguments; arga and argb
if we disregard the fact that you wrote std::cout >> instead of std::cout << (the latter is the correct form), we end up with two reasons for your described errors:
your compiler complains about std::cout << element[i] because no suitable overload is found to handle an entity of the type of element[i] and an std::ostream& (which is the underlying type of std::cout).
your compiler complains about std::cout << test (arga, argb) because there is no function in scope named test that takes two arguments corresponding to arga, argv. test, in your snippet, is a member-function that belongs to an entity, it's not callable by its own.
Welcome to C++.
First, the syntax for output is:
cout<<
instead of
cout>>
You are right in guessing that test is a function that returns boolean.Here elements[i] is a pointer pointing to a struct element which has this test function.
To learn C++, you can use these articles that I wrote.Good luck!
Since numerous respondents told me that I need to provide the code before they can answer, I looked deeper in the code, and re-wrote something which tells me that the line:
if (elements[i]->test(arga, argb)) {}
is a test to see whether or not the boolean member function of elements[i] is true.
The c++ program that I wrote to identify the meaning of -> in this context is:
#include "stdafx.h"
#include <vector>
#include <string>
#include <iostream>
template<typename T>
class Bone
{
public:
std::string myName;
int mySize;
Bone(const std::string &name, const int &size) : myName(name), mySize(size)
{}
bool isBigger(const int &testSize) const
{
if (testSize > mySize) return false;
else return true;
}
};
int main(int argc, char **argv)
{
std::vector<Bone<float> *> bones;
// name, location, size
bones.push_back(new Bone<float>("femur", 10));
bones.push_back(new Bone<float>("ulna", 4));
bones.push_back(new Bone<float>("maxilla", 3));
int testSize = 6;
// test each bone to see if it is bigger than testSize
for (unsigned i = 0; i < bones.size(); ++i) {
if (bones[i]->isBigger(testSize)) {
std::cout << bones[i]->myName; std::cout << " is bigger than testSize! " << std::endl;
}
}
while (!bones.empty()) {
Bone<float> *thisBone = bones.back();
bones.pop_back();
delete thisBone;
}
return 0;
}
Thank you to everyone who led me to figure this out.

converting a variable name to a string in C++

I'd like to output some data to a file. For example assume I have two vectors of doubles:
vector<double> data1(10);
vector<double> data2(10);
is there an easy way to output this to a file so that the first row contains the headings 'data1' and 'data2' followed by the actual contents. The function which
outputs the data will be passed various different arrays so hardcoding the name
of the heading is not possible - ideally I'd like to convert the variable name
to some string and then output that string followed by the contents of the vector array. However, I'm not sure how to convert the variable name 'data1' to a string,
or indeed if it can easily be done (from reading the forums my guess is it can't)
If this is not possible an alternative might be to use an associative
container such as map or perhaps more simply a 'pair' container.
pair<vector<double>,string> data1(10,'data1');
Any suggestions would be welcome!
You can use the preprocessor "stringify" # to do what you want:
#include <stdio.h>
#define PRINTER(name) printer(#name, (name))
void printer(char *name, int value) {
printf("name: %s\tvalue: %d\n", name, value);
}
int main (int argc, char* argv[]) {
int foo = 0;
int bar = 1;
PRINTER(foo);
PRINTER(bar);
return 0;
}
name: foo value: 0
name: bar value: 1
(Sorry for printf, I never got the hang of <iostream>. But this should be enough.)
try this:
#define GET_VARIABLE_NAME(Variable) (#Variable)
//in functions
int var=0;
char* var_name= GET_VARIABLE_NAME(var);
I had the same problem. After a little bit of experimentation I created following macros that convert names of variables, fields, functions, methods and types to strings.
#define MACRO_VARIABLE_TO_STRING(Variable) (void(Variable),#Variable)
#define MACRO_FUNCTION_TO_STRING(Function) (void(&Function),#Function)
#define MACRO_METHOD_TO_STRING(ClassName,Method) (void(&ClassName::Method),#Method)
#define MACRO_TYPE_TO_STRING(Type) (void(sizeof(Type)),#Type)
The code uses comma operator and void conversion to force compiler to check if variable, function, etc. really exists. The nice thing is that it works well with uninitialized variables too. I tested it on both VC and GCC with all pedantic options I found out without any warning messages.
int GetAndPrintValue(const char* VariableName)
{
std::cout << VariableName << std::endl;
return 10;
}
int Variable=GetAndPrintValue(MACRO_VARIABLE_TO_STRING(Variable));
I use such code when I write parsers that reads data from input stream and if parsed variable is out of bounds it throws an exception with name of variable that failed my validity checks.
Slightly adapted from #sarnold's answer, for C++:
#define DEBUG(x) std::cout << #x << " = " << x << std::endl;
An example program which uses this:
int main() {
int foo = 1;
DEBUG(foo);
return 0;
}
You can use the preprocessor, there's a stringify token, but it's only available from the source, not to a function (you'd get the argument name).
I had a similar quest. In Qt, I got tired of constantly writing the variable name as a string without autocomplete when writing to qDebug().
After a lot of trial and error with different macros and functions, I found that this macro works great:
#define PRINT(x) ", " << #x << ": " << x
Example usage:
int someVariable = 42;
double anotherVariable = 13.37;
qDebug().nospace() << "Some text" << PRINT(someVariable) << PRINT(anotherVariable);
Output:
Some text, someVariable: 42, anotherVariable: 13.37
I guess this (or something very similar) will work for std::cout as well.
A bit late to the party, but I hope this can help anyone out there!
I'd have thought the obvious answer is to make the function that performs the output take the heading text as a string parameter.
For this case I have made nameof() macro. It returns a std::string name of a variable, type or member. It works like nameof() in C#.
For Example:
#include "nameof.h"
std::vector<double> data1(10);
std::string name = nameof(data1); // "data1"
struct Foo1
{
struct Foo2
{
Foo1* foo1;
};
Foo1* foo1;
Foo2 foo2;
};
name = nameof(Foo1::foo1->foo2.foo1); // "foo1"
name = nameof(123); // std::logic_error exception