How to trace exceptions in a domain context in C++11? - c++

When an exception is thrown, it would be nice to be able to add information about how the error could happen, as the exception propagates up the call stack.
With information i don't mean technical info (e.g. Error in /src/foo.cpp:26), but something in context of the domain (e.g. Failed to load image "foo.png").
So instead of tracing the actual call stack, i want to provide my own information.
What's the best way to implement that in c++11?
I tried using nested exceptions with std::throw_with_nested() but the problem there is that if you want to catch some exceptions by their type only the outermost exception can be caught (I want the innermost).
Like in this example:
#include <iostream>
#include <exception>
void run()
{
try
{
throw 1;
}
catch(...)
{
std::throw_with_nested(std::runtime_error("run() failed"));
}
}
int main()
{
try {
run();
} catch(const int& e) {
// won't handle this error because only outermost exception can be caught
std::cerr << e << std::endl;
}
}
That is a problem, because the outer exceptions are only there to provid informartion, and only the innermost represents the actual error.

Related

Detecting whether or not a catch block is being executed

I have an error logging function that's used through existing code. If possible, I would like to improve it by detecting when it's called from a catch block to extract additional information from the exception when it's available. During a catch block you can rethrow the exception and catch it locally.
void log_error()
{
try {
throw; // Will rethrow the exception currently being caught
}
catch (const std::exception & err) {
// The exception's message can be obtained
err.what();
}
}
If you aren't in the context of a catch block, this function will call std::terminate. I'm searching for a way of detecting rather or not an exception exists to be rethrown, is it safe to call throw;? I've found std::uncaught_exception but it seems to only apply to functions being executed as part of throwing an exception and is useless within the catch block. I've read through http://en.cppreference.com/w/cpp/error but I can't seem to find any applicable mechanism.
#include <stdexcept>
#include <iostream>
struct foo {
// prints "dtor : 1"
~foo() { std::cout << "dtor : " << std::uncaught_exception() << std::endl; }
};
int main()
{
try
{
foo bar;
throw std::runtime_error("error");
}
catch (const std::runtime_error&)
{
// prints "catch : 0", I need a mechanism that would print 1
std::cout << "catch : " << std::uncaught_exception() << std::endl;
}
return 0;
}
Workarounds I've found include simply implementing a different function to be called from catch blocks but this solution wouldn't be retroactive. Another would be to use a thread_local flag with custom exception classes to know when the current thread has constructed an exception but not destroyed it, but this seems error prone and would be incompatible with standard and existing exception classes. Example for this weak workaround :
#include <exception>
struct my_base_except : public std::exception
{
my_base_except() { ++error_count; }
virtual ~my_base_except() { --error_count; }
my_base_except(const my_base_except &) { ++error_count; }
my_base_except(my_base_except&&) { ++error_count; }
static bool is_in_catch() {
return error_count > 0;
}
private:
static thread_local int error_count;
};
thread_local int my_base_except::error_count = 0;
void log_error()
{
if (my_base_except::is_in_catch())
{
// Proceed to rethrow and use the additional information
}
else
{
// Proceed with the existing implementation
}
}
Does a standard feature exists to solve this problem? If not, is there a more robust work-around than the ones I've identified here?
std::current_exception might be what you are looking for.
std::current_exception returns an std::exception_ptr, which is a pointer type to the current handled exception, or nullptr if no exception is being handled. The exception can be rethrown with std::rethrow_exception.

How to cause C++ throw to dump core if the exception would be handled by a particular catch block

Is there a way to cause a throw in C++ to dump core at the throw site if the thrown exception would be handled by a certain catch block? I would like something similar to what happens with g++ when an exception reaches the top level.
For example, I would like something like this:
try {
bar();
try {
foo();
} catch(...) {
# pragma dump_at_throw_site
}
} catch(...) {
std::cerr << "There was a problem" << std::endl;
}
This way, if any exception thrown from foo() or its callee's that reaches the call-site of foo() would cause a core dump at the throw site so one can see who threw the exception that made it to the to this level.
On the other hand, exceptions thrown by bar() would be handled normally.
Yes,it can in Windows. I don't know Linux, suppose it can also.
We can register a Exception Handler function to response the throw before the catch
Here is the code example:
#include <iostream>
#include "windows.h"
#define CALL_FIRST 1
LONG WINAPI
VectoredHandler(
struct _EXCEPTION_POINTERS *ExceptionInfo
)
{
UNREFERENCED_PARAMETER(ExceptionInfo);
std::cout <<"VectoredHandler"<<std::endl;
return EXCEPTION_CONTINUE_SEARCH;
}
int main()
{
PVOID handler;
handler = AddVectoredExceptionHandler(CALL_FIRST,VectoredHandler);
try {
throw 1;
}catch(...)
{
std::cout <<"catch (...)"<< std::endl;
}
RemoveVectoredExceptionHandler(handler);
std::cout << "end of main"<<std::endl;
return 0;
}
The outputs of code are:
VectoredHandler
catch (...)
end of main
So,you can dump core int the function VectoredHandler.
The VectoredHandler is called after the debugger gets a first chance notification, but before the system begins unwinding the stack.
And if your purpose is just to debug the problem issue, then you can rely on the debugger feature to handle the first chance exception, don't need dump the application.
For your information, you may need know What is a First Chance Exception? in windows to understand how windows dispatch the exception.

intermixing c++ exception handling and SEH (windows)

I have a function in which I call getaddrinfo() to get an sockaddr* which targets memory is allocated by the system.
As many may know, you need to call freeaddrinfo() to free the memory allocated by getaddrinfo().
Now, in my function, there are a few places, where I may throw an exception, because some function failed.
My first solution was to incorporate the freeaddrinfo() into every if-block.
But that did look ugly for me, because I would have had to call it anyways before my function returns, so I came up with SEH`s try-finally...
But the problem I encountered is, that it is not allowed to code the throw-statements into the __try-block
Then, I read on the msdn and tried to swap the throw-statements into the helper function called from within the __try-block... and voila, the compiler didn´t moan it anymore...
Why is that? And is this safe? This does not make sense to me :/
Code:
void function()
{
//...
addrinfo* pFinal;
__try
{
getaddrinfo(..., &pFinal);
//if(DoSomething1() == FAILED)
// throw(exception); //error C2712: Cannot use __try in functions that require object unwinding
//but this works
Helper();
//...
}
__finally
{
freeaddrinfo();
}
}
void Helper()
{
throw(Exception);
}
EDIT:
tried the following and it works with throwing an integer, but does not when i use a class as an exception:
class X
{
public:
X(){};
~X(){};
};
void Helper()
{
throw(X());
}
void base()
{
__try
{
std::cout << "entering __try\n";
Helper();
std::cout << "leaving __try\n";
}
__finally
{
std::cout << "in __finally\n";
}
};
int _tmain(int argc, _TCHAR* argv[])
{
try
{
base();
}
catch(int& X)
{
std::cout << "caught a X" << std::endl;
}
std::cin.get();
return 0;
}
Why? :/
You can't mix the two exception types. Under the covers, C++ exceptions use SEH and your SEH exception handler could mess up the exception propogation logic. As a result, the C++ compiler won't allow you to mix them.
PS: Structured Exception Handling is almost always a VERY bad idea. Internally Microsoft has banned the use of SEH except in very limited circumstances. Any component that does use structured exception handling is automatically subject to intense code reviews (we have tools that scan code looking for its use to ensure that no cases are missed).
The problem with SEH is that it's extremely easy to accidentally introduce security vulnerabilities when using SEH.
You could wrap the addrinfo in a class that calls getaddrinfo in the constructor and freeaddrinfo in its destructor.
That way it will always be freed, whether there is an exception thrown or not.
catch(int& X)
{
std::cout << "caught a X" << std::endl;
}
That doesn't catch an X, it catches an int&. Since there is no matching catch block, the exception is uncaught, stack unwinding doesn't occur, and __finally handlers don't run.
You can put catch (...) in your thread entrypoint (which is main() for the primary thread) in order to make sure that stack unwinding occurs, although some exceptions are unrecoverable, that's never true of a C++ exception.

a small issue in using exception handling in c++

The below given simple exception program is giving Unhandled Exception "Microsoft C++ exception: int at memory location 0x0012fe94..". I am getting this error immediately after the function excep() is returned.
Please can anyone tell why this error is coming here. Also it will be helpful if all the possible mistakes in this code were explained/analysed. I am learning to code better.
I am using Visual C++ 2005.
#include <iostream>
using namespace std;
int main ()
{
int excep(int);
throw excep(20);
return 0;
}
int excep(int e)
{
cout << "An exception occurred. Exception Nr. " << e << endl;
return 0;
}
If you try to learn exception throwing/handling your code contains an error.
function excep must handle object that was thrown not to be thrown itself.
your code must be rewritten as follows:
using namespace std;
int excep(int e)
{
cout << "An exception occurred. Exception Nr. " << e << endl;
return 0;
}
int main ()
{
int excep(int);
try
{ // <--------- Begin of try block. required part of the exception handling
throw 20;
}
catch (const int &errCode) // <------- we are catching only ints
{
excep(errCode); // Function that handles exception
}
return 0;
}
It is good design not to throw int variables, but type that inherites std::exception. But this is more advanced exception using knowledge
What did you expect to happen?
You call a function which prints out "An exception occurred", plus the other text, and then you throw the resulting value as an exception, which you never catch, so the program reports than an uncaught exception was thrown. Which is true, because that's exactly what you just did.
The entire point in exceptions is that when you throw an exception, it will propagate out through the program, until it is either handled, or it reaches the top level and terminates the program. You don't handle the exception, so it terminates the program.
If you want to handle an exception, you need to wrap the throwing code in a try block, followed by a catch, as in:
try {
throw excep(20);
}
catch (int ex) {
// do something about the exception
}
In the line
throw excep(20);
excep(20) is called first, whose return value is then thrown, i.e. you throw an integer. It is roughly equivalent to:
const int i = excep(20);
throw i;
To get you an idea how exception-snytax looks:
#include <iostream>
#include <stdexcept>
using namespace std;
int main ()
{
try {
// do something
throw std::runtime_error("test");
} catch (const std::exception &e) {
std::cout << "exception: " << e.what() << std::endl;
}
}
In practive: NEVER throw anything that is not derived from std::exception.
Proposed Readings:
Introductory book on C++ (search stackoverflow for this)
C++ FAQ on Exception Handling
"Exceptional C++" (for advanced C++ users)

why does throw "nothing" causes program termination?

const int MIN_NUMBER = 4;
class Temp
{
public:
Temp(int x) : X(x)
{
}
bool getX() const
{
try
{
if( X < MIN_NUMBER)
{
//By mistake throwing any specific exception was missed out
//Program terminated here
throw ;
}
}
catch (bool bTemp)
{
cout<<"catch(bool) exception";
}
catch(...)
{
cout<<"catch... exception";
}
return X;
}
private:
int X;
};
int main(int argc, char* argv[])
{
Temp *pTemp = NULL;
try
{
pTemp = new Temp(3);
int nX = pTemp->getX();
delete pTemp;
}
catch(...)
{
cout<<"cought exception";
}
cout<<"success";
return 0;
}
In above code, throw false was intended in getX() method but due to a human error(!) false was missed out. The innocent looking code crashed the application.
My question is why does program gets terminated when we throw "nothing”?
I have little understanding that throw; is basically "rethrow" and must be used in exception handler (catch). Using this concept in any other place would results into program termination then why does compiler not raise flags during compilation?
This is expected behaviour. From the C++ standard:
If no exception is presently being
handled, executing a throw-expression
with no operand calls
terminate()(15.5.1).
As to why the compiler can't diagnose this, it would take some pretty sophisticated flow analysis to do so and I guess the compiler writers would not judge it as cost-effective. C++ (and other languages) are full of possible errors that could in theory be caught by the compiler but in practice are not.
To elaborate on Neil's answer:
throw; by itself will attempt to re-raise the current exception being unwind -- if multiple are being unwound, it attempts to rethrow the most recent one. If none are being unwound, then terminate() is called to signal your program did something bogus.
As to your next question, why the compiler doesn't warn with throw; outside a catch block, is that the compiler can't tell at compile-time whether the throw; line may be executing in the context of a catch block. Consider:
// you can try executing this code on [http://codepad.org/pZv9VgiX][1]
#include <iostream>
using namespace std;
void f() {
throw 1;
}
void g() {
// will look at int and char exceptions
try {
throw;
} catch (int xyz){
cout << "caught int " << xyz << "\n";
} catch (char xyz){
cout << "caught char " << xyz << "\n";
}
}
void h() {
try {
f();
} catch (...) {
// use g as a common exception filter
g();
}
}
int main(){
try {
h();
} catch (...) {
cout << "some other exception.\n";
}
}
In this program, g() operates as an exception filter, and can be used from h() and any other function that could use this exception handling behavior. You can even imagine more complicated cases:
void attempt_recovery() {
try{
// do stuff
return;
} catch (...) {}
// throw original exception cause
throw;
}
void do_something() {
for(;;) {
try {
// do stuff
} catch (...) {
attempt_recovery();
}
}
}
Here, if an exception occurs in do_something, the recovery code will be invoked. If that recovery code succeeds, the original exception is forgotten and the task is re-attempted. If the recovery code fails, that failure is ignored and the previous failure is re-throw. This works because the throw; in attempt_recovery is invoked in the context of do_something's catch block.
From the C++ standard:
15.1 Throwing an exception
...
If no exception is presently being
handled, executing a throw-exception
with no operand calls terminate()
The reason the compiler can't reliably catch this type of error is that exception handlers can call functions/methods, so there's no way for the compiler to know whether the throw is occurring inside a catch. That's essentially a runtime thing.
I have little understanding that throw; is basically "rethrow" and must be used in exception handler (catch). Using this concept in any other place would results into program termination then why does compiler not raise flags during compilation?
Rethrowing is useful. Suppose you have a call stack three levels deep with each level adding some context resource object for the final call. Now, when you have an exception at the leaf level, you will expect some cleanup operation for whatever resources the object has created. But this is not all, the callers above the leaf may also have allocated some resources which will need to be deallocated. How do you do that? You rethrow.
However, what you have is not rethrow. It is a signal of giving up after some failed attempts to catch and process any and all exceptions that were raised.
A throw inside of a catch block with no args will re-throw the same exception that was caught, so it will be caught at a higher level.
A throw outside of a catch block with no args will cause a program termination.
To complete the previous answers with an example of when/why the compiler cannot detect the problem:
// Centralized exception processing (if it makes sense)
void processException()
{
try {
throw;
}
catch ( std::exception const & e )
{
std::cout << "Caught std::exception: " << e.what() << std::endl;
}
catch ( ... )
{
std::cout << "Caught unknown exception" << std::endl;
}
}
int main()
{
try
{
throw 1;
}
catch (...)
{
processException(); // correct, still in the catch clause
}
processException(); // terminate() no alive exception at the time of throw.
}
When compiling the function processException the compiler cannot know how and when it will be called.
You don't have anything to catch, and so the exception bubbles all the way up. Even catch(...) needs something.