5

Possible Duplicate:
How to print message from caught exception?

Apologies if this is basic or duplicated - I did several searches first but didn't find anything that answered this.

If I do something basic like:

throw exception("This thing didn't work");

Where can I see that? The string doesn't show up in the output console, stack trace, or any of the .log files associated with the project. Makes me wonder why I'm even putting a string there if it can't be seen anywhere. I can of course use the stack trace to see where it blew up, but that kind of defeats the purpose of having exceptions in the first place.

In Java, when I give it a string, I'll see that string in the output somewhere. I just wonder if it's possible to reproduce this behavior in C++.

Community
  • 1
  • 1
Darrel Hoffman
  • 4,436
  • 6
  • 29
  • 41
  • 1
    I think it can be seen when the exception is caught. Other than that, probably crash dump? – nhahtdh Jul 31 '12 at 15:46
  • 1
    You *are* catching the exception, are you? – Kerrek SB Jul 31 '12 at 15:55
  • 2
    Technically that is not valid. You are using a bug in the MS libray (std::exception does not have a constructor that takes a string). But your point is valid if you change to `std::runtime_error("This thing didn't work")`. – Martin York Jul 31 '12 at 16:13

2 Answers2

5

std::exception() has a member function called what(). See:

http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-3.3/classstd_1_1exception.html

For things like std::logic_error, it returns the text you passed into the constructor.

Stuart Golodetz
  • 20,238
  • 4
  • 51
  • 80
1

You must catch the exception in order to see the string. It can be useful to have an exception handler of last resort as follows:

int main(int argc, char **argv)
{
    try {
        ...
    }
    catch(const std::exception& e) {
        std::cout << "Uncaught exception: " << e.what() << std::endl;
    }
}

In a GUI application you can have a catch statement in the main event loop, and display the error message in a message box.

In an event-driven non-GUI application you can also have a catch statement in the main event loop, and write the error message to a log file.

These methods will make sure that you see all exceptions. Of course, most exceptions should be caught before they reach your exception handler of last resort.

Johan Råde
  • 20,480
  • 21
  • 73
  • 110
  • This is probably it. Problem is that some of the crashes are caused by asserts in libraries, and there seems to be no way of catching those, so even a last-resort try/catch doesn't catch everything... – Darrel Hoffman Jul 31 '12 at 17:26