Note that there are some explanatory texts on larger screens.

plurals
  1. POclear explanation sought: throw() and stack unwinding
    primarykey
    data
    text
    <p>I'm not a programmer but have learned a lot watching others. I am writing wrapper classes to simplify things with a really technical API that I'm working with. Its routines return error codes, and I have a function that converts those to strings:</p> <pre><code>static const char* LibErrString(int errno); </code></pre> <p>For uniformity I decided to have member of my classes throw an exception when an error is encountered. I created a class:</p> <pre><code>struct MyExcept : public std::exception { const char* errstr_; const char* what() const throw() {return errstr_;} MyExcept(const char* errstr) : errstr_(errstr) {} }; </code></pre> <p>Then, in one of my classes:</p> <pre><code>class Foo { public: void bar() { int err = SomeAPIRoutine(...); if (err != SUCCESS) throw MyExcept(LibErrString(err)); // otherwise... } }; </code></pre> <p>The whole thing works perfectly: if <code>SomeAPIRoutine</code> returns an error, a try-catch block around the call to <code>Foo::bar</code> catches a standard exception with the correct error string in <code>what()</code>. </p> <p>Then I wanted the member to give more information:</p> <pre><code>void Foo::bar() { char adieu[128]; int err = SomeAPIRoutine(...); if (err != SUCCESS) { std::strcpy(adieu,"In Foo::bar... "); std::strcat(adieu,LibErrString(err)); throw MyExcept((const char*)adieu); } // otherwise... } </code></pre> <p>However, when <code>SomeAPIRoutine</code> returns an error, the <code>what()</code> string returned by the exception contains only garbage. It occurred to me that the problem could be due to <code>adieu</code> going out of scope once the <code>throw</code> is called. I changed the code by moving <code>adieu</code> out of the member definition and making it an attribute of the class <code>Foo</code>. After this, the whole thing worked perfectly: a try-call block around a call to <code>Foo::bar</code> that catches an exception has the correct (expanded) string in <code>what()</code>.</p> <p>Finally, my question: what exactly is popped off the stack (in sequence) when the exception is thrown in the if-block when the stack "unwinds?" As I mentioned above, I'm a mathematician, not a programmer. I could use a really lucid explanation of what goes onto the stack (in sequence) when this C++ gets converted into running machine code. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload