Exception class fails with recursive function - c++

I have an exception class called Exception, and I'm invoking a recursive function which gets called approximately 200 times while looping through a map. RecursiveFunction() is part of a class that contains a parameters map (which maps a string to a class param). The class param contains a min, a max, and number of steps between min and max, so that a set of functions can be run with each parameter set. RecursiveFunction() therefore loops through the map to run a set of functions given the 'current' parameters.
bool RecursiveFunction(map<string,param>::iterator current) {
map<string,param>::iterator last = parameters.end();
last--;
if( current == last )
return true;
else {
// Do some things
if(something_wrong)
throw Exception("RecursiveFunction()","Something went wrong");
++current;
RecursiveFunction(current);
}
}
The code above fails after about 120 recursive calls. It seems to be a memory issue, because most of the time it fails on the line:
last--;
The weird thing is that the code runs smoothly in both of the following cases:
bool RecursiveFunction(map<string,param>::iterator current) {
...
if(something_wrong)
throw "";
...
}
or
bool RecursiveFunction(map<string,param>::iterator current) {
...
if(something_wrong) {
Exception exc = Exception("RecursiveFunction()","Something went wrong");
ThrowException(exc); //ThrowException() { throw exc; }
}
...
}
The code isn't hitting the 'throw' so the Exception is not being constructed or copied (confirmed with breakpoints). Why would the existence of a class affect the outcome of a function, if that class isn't getting instantiated in the function?
EDIT:
I was able to reproduce this using a complete example (with Visual Studio 2010):
#include <iostream>
using namespace std;
class Exception: public std::exception {
private:
char gsCallPath[1001];
char gsError[1001];
public:
Exception(const char* sErrorCallPath, const char* sThrownError)
{
strcpy(gsError,sThrownError);
strcpy(gsCallPath,sErrorCallPath);
}
~Exception() {
}
};
bool RecursiveFunction(int n);
int main() {
RecursiveFunction(500);
}
bool RecursiveFunction(int n) {
cout << n << '\n';
if (n == 0)
return true;
else {
if(false) {
throw Exception("","");
//throw "";
}
else
{
RecursiveFunction( n-1 );
}
}
}
The run crashed with a Stack Overflow exception. Replacing throw Exception("",""); with throw ""; allowed the program to run to completion. Note: the size of the Exception class had an impact on how big n needed to be in order to overflow. Thanks #catscradle and #Yakk for your comments.

#include <exception>
void f() {
if (false) {
throw "";
//throw std::exception();
}
return f();
}
int main() {
f();
}
Looking at the assembly, it seems that the function reserves stack space for the exception object and it doesn't matter if it gets thrown or not. So in case of "" this function reserves 204 bytes(sub esp, 0CCh) and in case of std::exception it's sub esp, 0D4h, i.e. 8 bytes more, which is sizeof(std::exception) - sizeof(char*).

Related

Transfer values from one stack to another keeping the same order in C++

#include <iostream>
#include<stdlib.h>
#include <stack>
using namespace std;
const int MAX = 1000;
class Stack
{
int top=-1;
int arr[MAX];
public:
void push(int value)
{
if (top > MAX - 1)
cout << "Stack Overflow";
else
arr[top++] = value;
}
int pop()
{
if (top == -1)
cout << "Stack Underflow";
else
return arr[top--];
}
void StackTransfer(stack <int> &s1, stack <int> &s2)
{
int x;
if (s1.empty())
return;
x = s1.top();
s1.pop();
StackTransfer(s1, s2);
s2.push(x);
}
};
int main()
{
stack <int> st1, st2, st3;
st1.push(10);
st1.push(20);
st2.push(30);
st2.push(40);
cout<<st3.StackTransfer(&st1, &st2);
}
I want to transfer values, but when I call StackTransfer() function in main (), I am getting this error
Severity Code Description Project File Line Suppression State
Error (active) E0135 class "std::stack<int, std::deque<int, std::allocator>>" has no member "StackTransfer"
Is the logic of StackTransfer() correct for transferring values and preserving the order same?
You made several mistakes in your code.
The first one is mismatching the class names: you declare an ordinary class Stack and then you use a templated class stack<int>. Those are two unrelated classes and the compiler is absolutely right when it complains the stack<int> class does not have a StackTransfer method.
The second mistake is a way you try to call the method. Either the method acts on an object and then:
(a) there's only one explicit parameter to it (another one is this),
(b) its name should indicate a direction of the action: void StackTransferFrom(Stack &s) or void StackTransferTo(Stack &s),
(c) the parameter should be the same class (Stack, not stack<int>), and
(d) it will be called on some object of the declared class: Stack s1, s2; ....; s1.StackTransferFrom(s2);
or the method acts on two objects and then:
(a) it should be defined as static, and
(b) it will be called with two arguments: Stack::StackTransfer(s1, s2); without any third object, but
(c) with a class identifier.
Another one is using the ampersand operator & when calling the function. Your method has reference-type parameters, not pointers, so you should call it with references to variables: StackTransfer(s1, s2) not with pointers to them: StackTransfer(&s1, &s2). The latter would work with a static void StackTransferTo(Stack *s1, Stack *s2) method.
Your attempt to send the result to standard output is wrong, too – your function is declared void, which means it returns no value, hence you get nothing from it that could be output to cout.
Yet another mistake lurks in the push() method: you used a post-increment operator there, but the initial value of top is minus-one. As a result the first value push-ed to your stack will be written to arr[-1], before the array's beginning. This triggers Undefined Behavior of your program.
Improved version:
#include <iostream>
const int MAX = 1000;
class Stack
{
int top = -1;
int arr[MAX];
public:
void push(int value)
{
if (top >= MAX - 1)
std.cout << "Stack Overflow\n";
else
arr[++top] = value;
}
int pop()
{
if (top < 0)
std.cout << "Stack Underflow\n";
else
return arr[top--];
}
bool empty()
{
return top == -1;
}
int top()
{
if (empty())
{
std.cout << "Stack is empty\n";
return 0;
}
return arr[top];
}
void StackTransfer(Stack &source)
{
if (source.empty())
return;
int x = source.top();
source.pop();
StackTransfer(source);
push(x);
}
};
int main()
{
Stack st1, st2;
st1.push(10);
st1.push(20);
st2.push(30);
st2.push(40);
st2.StackTransfer(st1);
}

Nested try/catch blocks for error propagation across classes?

I have a class interface function which implements other functions within the class in a specific order:
class Child
{
public:
auto Interface()->bool
{
this->F1(); //I use this just for extra clarity (e.g. not calling global function)
this->F2();
return true;
}
auto F1()->void
{
//Do stuff...
}
auto F2()->void
{
//Do more stuff...
}
};
class Parent
{
public:
Child ChildObj;
auto CallUponChild()->void
{
bool success = ChildObj.Interface();
}
};
I want to wrap the 'Interface()' implementation in a try/catch block:
auto Interface()->bool
{
try{
this->F1();
this->F2();
}catch(...){
//Handle
}
}
However, on the occurance of an error, I wish to attempt the function again, and if that errors, I want to propogate the error back to the Parent class:
auto Interface()->bool
{
int error_count=0;
try{
try{
this->F1();
this->F2();
return true;
}catch(...){
if(error_count<1){this->F1(); this->F2();}
else{throw "Out of tries";}
}
}catch(...){
return false;
}
}
Is using nested try/catch blocks fround upon? Is this the best approach to take?
Something like
auto Interface()->bool
{ int error_count=0;
while (error_count < 1) {
try {
this->F1();
this->F2();
return true;
}
catch(...){
// if (error_count >= 1)
// throw; // to throw original exception
++error_count;
}
};
// throw "Out of tries"; // to throw "Out of tries" exception
return false; // to use the boolean result
}
should be sufficient. If F1() throws an exception in your catch block, your function will return false without incrementing error_count.
It does not seems to be something that the child should handle imho, should that behaviour been handled by the Parent which knows how to deal with their childs? I would go this way:
auto CallUponChild()->void
{
const bool success = ChildObj.Interface();
if (!success) { // maybe if-init if you have a c++17 compiler
// try again
ChildObj.Interface();
}
}
I think the way to handle the child objects should be at Parent level as I said, Child object should do one thing and if it's needed to be done twice(or N) then should'n be their responsibility.
If you want to show how the exception were thrown you can have a look at this:
http://en.cppreference.com/w/cpp/error/throw_with_nested

reduce if statements when checking result

My C++ function has many if statements checking the returning value of called functions:
Result func(...){
if (SUCCESS != func1(...))
return ERROR;
// do something
if ( SUCCESS != func2(...))
return ERROR;
// do something else
if (SUCCESS != func3(...))
return ERROR;
// do something
.
.
.
}
Is there anyway for eliminating or reducing the if statements here?
For example I want something like this:
Result func(...){
Result result = SUCCESS;
when (result != SUCCESS) return ERROR;
result = func1(...);
// do something
result = func2(...);
// do something else
result = func3(...);
// do something
.
.
.
}
I cannot help myself, but to write solution which might be considered over-engineering, but it allows to prepare single template class for all results (for future use) and then minimize code for actual usage (no need to use checking methods or macros, no need to write own wrappers except this single result holder template class). Enjoy :D.
#include <iostream>
template<class T>
class Result
{
public:
Result() :
m_value(),
m_badValue()
{
}
Result(const T& value, const T& badValue) :
m_value(value),
m_badValue(badValue)
{
}
void operator=(const T& value)
{
if(value == m_badValue)
{
throw "Bad Value!";
}
else
{
m_value = value;
}
}
operator const T&() const
{
return m_value;
}
const T& value() const
{
return m_value;
}
private:
T m_value;
T m_badValue;
};
static const int SUCCESS = 0;
static const int FAIL = -1;
int func1()
{
return SUCCESS;
}
int func2()
{
return SUCCESS;
}
int func3()
{
return FAIL;
}
int main()
{
Result<int> result(FAIL, FAIL);
try
{
result = func1();
result = func2();
result = func3();
}
catch (const char *error)
{
::std::cout << "Error: " << error << ::std::endl;
}
::std::cout << "Last value: " << static_cast<int>(result) << " - " <<
((result == SUCCESS) ? "SUCCESS" : "FAIL") << ::std::endl;
}
Note: you should throw only what derives from ::std::exception, but I used const char* to simplify things and prepare working example.
Since you are coding in C++, not in C, the option of throwing exceptions is available to you. Making the code look better while responding to exceptional situations properly was the primary driving force behind the feature.
In situations when you use third-party APIs that do not offer exceptions you could wrap their functions into your functions that throw exceptions, like this:
void func1w(...) {
if (SUCCESS!=func1(...)) throw my_exception();
}
void func2w(...) {
if (SUCCESS!=func2(...)) throw my_exception();
}
...
void caller() {
try {
func1w();
func2w();
func3w();
} catch (my_exception& e) {
cerr << "Error!" << endl;
}
}
Note that the function that calls exception-throwing wrappers could stay away from checking exception codes altogether, letting the higher-level function deal with them. The general rule with exceptions is that the code should not catch exceptions unless it knows how to handle them.
You can also define a macro:
#define MUST_SUCCEED(x) if(SUCCESS!=(x))return ERROR
This comes at the cost of reduced readability, because the macro is not instantly familiar to the readers of your code:
MUST_SUCCEED(func1(...));
MUST_SUCCEED(func2(...));
MUST_SUCCEED(func3(...));
Short answer: no
Long answer: no, that's how you do it in every structured programming language that I'm aware of.
Alternative: if all functions involved (func1, func2, func3) would throw exceptions instead of returning a status code then you wouldn't have to use ifs. Your function func would just propagate any exception that was thrown from within it.
Edit, expanding on Tony's comment:
Alternative #2: involved functions do not throw exceptions, but your function could. Suppose you have a helper function like this:
void CheckResult(Result result)
{
if (result != SUCCESS)
throw SomeException(result);
}
Your function would then look like this:
void func(...)
{
CheckResult(func1(...));
// do something
CheckResult(func2(...));
// do something else
CheckResult(func3(...));
// do something
}
So, the if's are not avoided but moved to another function, so that your function is free of them.
You could make a vector of function pointers containing func1(), func2() etc., then iterate through all the elements in this vector by means of for loop, calling each function and comparing the value returned against SUCCESS. Then, if the return value of any function does not equal SUCCESS, you can set a flag to a value indicating error (in your example this flag would be of the name 'result').

How to tell that there is no result of a function with return value?

I have a short question. Given a function which returns an object of a class as result, what should I return if there is no result (say because an index is out of range)? I could return a new "empty" object but how can I point out that there was no successful calculation?
I suppose there is a common approach.
The common approach in C++ is either to throw an exception or to use some wrapper like boost::optional.
An exception should be thrown if it is some kind of error, the boost::optional-approach is more appropriate if it is a valid use-case of your function to return an empty result. One example that comes to mind is SQL's NULL. boost::optional turned out quite handy in our codebase.
Going by the philosophy of the vector::at method throw out_of_range exception if possible.
If we are talking about erroneous situation, throwing an exception is proper solution.
#include<exception>
Object * GenerateObject(int i)
{
if (i < 0)
throw std::out_of_range("i");
return new Object(i);
}
int main(int argc, char * argv[])
{
try
{
Object * obj = GenerateObject(-1);
// Succeeded
return 0;
}
catch (std::exception & e)
{
// Failed, exiting with error value
return 1;
}
}
If an empty value is allowed, you can specify a specific value for this class, eg.
class Rectangle
{
private:
int left, top, width, height;
public:
Rectangle(l, t, w, h)
{
left = l;
top = t;
width = w;
height = h;
}
public static Rectangle empty;
}
Rectangle Rectangle::empty = Rectangle(0, 0, -1, -1);
// ...
Rectangle DoSth(int i)
{
// i < 0 is NOT considered an error here
if (i < 0)
return Rectangle::empty;
// Further processing
}
It depends on what the semantics of the operation is.
If an error occurred, you should definitely throw an exception:
#include <stdexcept> // Necessary for standard exceptions
X foo()
{
...
if (/* something goes wrong... */)
{
// There may be a more appropriate exception class. You could
// also derive your own exception class from std::exception...
throw std::logic_error("Whatever!");
}
...
}
...
try
{
X x = foo();
// Work with x...
}
catch (std::logic_error const& e) // Catch what is appropriate...
{
std::cout << e.what();
}
If returning a no-value does not denote an error condition, you could use Boost.Optional. Alternatively, provided you can create an "empty" object of type X, you could think of returning a pair whose second member is a bool flag that tells whether the first member is a valid object or not, as below:
std::pair<X, bool> foo();
...
bool valid;
X x;
std::tie(x, valid) = foo();
if (valid)
{
// Use x...
}
You can throw an exception when values don't match expected results.
A tutorial can be found at http://www.cplusplus.com/doc/tutorial/exceptions
An exception works with a try and catch principle.
A program "tries" to execute code.
If something unexpected happens the executed code "throws" an object, variable or whatever and this will be caught.
In the catch statement you can place code what should happen if the unexpected has happened.
Just follow the tutorial.
You can pair an enumeration with the object type being returned. If the returned enumeration is a certain value, the object is valid, otherwise the object is in an invalid state.
// This is a working C++11 example.
#include <utility>
#include <memory>
enum result
{
ok,
out_of_range,
some_other_error
};
class object
{
public:
object() {}
};
typedef std::shared_ptr< object > object_ptr;
typedef std::pair< result, object_ptr > return_type;
return_type some_function( int index )
{
if ( index > 5 )
{
return return_type{ result::out_of_range, nullptr };
}
return return_type{ result::ok, object_ptr{ new object() } };
}
int main()
{
return_type res = some_function( 10 );
if ( res.first == result::ok )
{
// Do something with res.second
}
else
{
// Handle the error
}
}
I would probably just throw an exception instead.

How do I extract any information from boost::errinfo_nested_exception?

I have recently started using boost::exception. Now I would like to use boost::errinfo_nested_exception to print information about the cause of the error. The problem is I can't figure out how to get information from the cause. I have tried the following with no success:
#include <iostream>
#include <boost/exception/all.hpp>
struct myex : public virtual boost::exception {};
int main()
{
myex cause;
cause << boost::errinfo_file_name("causefile.cpp");
try {
myex ex;
ex << boost::errinfo_nested_exception(boost::copy_exception(cause));
throw ex;
}
catch (myex& e) {
// Here I would like to extract file name from cause and print
// it in a nice way, but I cant figure out what to do with a
// boost::exception_ptr.
const boost::exception_ptr* c =
boost::get_error_info<boost::errinfo_nested_exception>(e);
// I cant do this:
// const std::string* file = boost::get_error_info<boost::errinfo_file_name>(*c);
// Nor this:
// const std::string* file = boost::get_error_info<boost::errinfo_file_name>(**c);
// This works fine and the nested exception is there, but that's not what I want.
std::cout << boost::diagnostic_information(e) << std::endl;
}
return 0;
}
You need to rethrow the nested exception and examine that:
const boost::exception_ptr* c =
boost::get_error_info<boost::errinfo_nested_exception>(e);
if(c) try {
boost::rethrow_exception(*c);
} catch(boost::exception const& e) { // or a type derived from it
const std::string* file = boost::get_error_info<boost::errinfo_file_name>(e);
// ...
} catch(...) {
// presumably you don't want the exception to escape if it is
// not derived from boost::exception
}
I personally use a get_error_info wrapper that returns the result of boost::get_error_info<some_error_info>(e), or if nothing is found the result of get_error_info<some_error_info>(nested) (recursive call here) or 0 if there is no nested exception (or it is not error_info-enabled).
Alternatively/as a complement, you can factor the checking code above (the different catch clauses) in a function:
std::string const* // or return a tuple of what you examined etc.
examine_exception()
{
try {
throw; // precondition: an exception is active
} catch(boost::exception const& e) {
// as above
return ...;
}
}
boost::diagnostic_information is the correct way to get a description afaik.
But you could also overload to_string for boost::error_info(T):
http://svn.boost.org/svn/boost/trunk/boost/exception/errinfo_errno.hpp