How to throw with some printout in C++ - c++

If I just simply use throw some_string; then I get terminate called after throwing an instance of 'std::string'. How can I get some printout with the string value actually shown, for example, terminate called after throwing 'This is wrong', or something similar?
Thank you.

Generally, you should be throwing subclasses of std::exception. Most C++ implementations automatically print out the result of calling exception::what() if the exception is uncaught.
#include <stdexcept>
int main()
{
throw std::runtime_error("This is wrong");
}
With GCC, this outputs:
terminate called after throwing an instance of 'std::runtime_error'
what(): This is wrong
Aborted

You have to add code somewhere to deal with the thrown object. If you do nothing the program ends in calling abort and the result of that is implementation defined. The solution for you is to add a catch block somewhere in your code, for example in your main function. Here's why
You can catch the object you threw and construct a meaningful error message.
The default behavior results in terminating the program immediately without unwinding the stack and cleaning up. The object that is throw must be caught somewhere before main returns in order to avoid this.

You have to catch the exception
#include <iostream>
#include <string>
int main(int argc, char *argv[]) try
{
throw std::string("This is a test");
return 0;
}
catch(const std::string &s)
{
std::cout << s << std::endl;
}

Related

Throwing an exception when another exception has not been handled yet. (C++)

As far as I know, throwing an exception when another has not been handled yet is undefined behavior, and the program may crash. An exception is considered unhandled until it gets into the catch-block. I have the following code snippet:
#include <iostream>
using namespace std;
class ThrowingInDestructorClass
{
public:
ThrowingInDestructorClass() = default;
~ThrowingInDestructorClass() {
try {
throw std::runtime_error("2-nd exception. ");
}
catch(...)
{
std::cout << "Catched an error during Throwing class cleanup. " << std::endl;
};
}
};
void doSmth()
{
try {
ThrowingInDestructorClass throwing;
throw std::runtime_error("1-St exception. ");
}
catch(...)
{
std::cout << "Catched an error during doSmth. " << std::endl;
};
}
int main() {
doSmth();
}
Here we have a class that can throw and handle an exception inside its destructor, so it is OK. But we have a method that creates objects and throws an exception. During stack-unwinding, the class destructor will be called, throwing a 2-nd exception. So the 1-St exception will be unhandled yet.
When I run it, I get the following output:
Caught an error during Throwing class cleanup.
Caught an error during doSmth.
It may seem that everything is fine, but I'm not entirely sure that there is no UB here.
Could someone help to clarify the situation?
This answer is mostly just a summary of the comments:
I'll go through the program step by step starting at the point the first exception is thrown:
Stack unwinding begins by destroying the "throwing" object.
The destructor of the "throwing" object gets called, throwing another exception.
Stack unwinding finds a catch block for the new exception immediately, handling the exception. The destructor exits normally.
The stack unwinding finds the catch block for the first exception, handling it.
doSmth() exits normally
No function exited with an exception, thereby the condition
"...If any function that is called directly by the stack unwinding mechanism, after initialization of the exception object and before the start of the exception handler, exits with an exception, std::terminate is called. ..." en.cppreference.com/w/cpp/language/throw - Richard Critten
isn't met.
And even if you remove the try catch in the destructor, no UB will occur:
#include <iostream>
using namespace std;
class ThrowingInDestructorClass
{
public:
ThrowingInDestructorClass() = default;
~ThrowingInDestructorClass() {
throw std::runtime_error("2-nd exception. ");
}
};
void doSmth()
{
try {
ThrowingInDestructorClass throwing;
throw std::runtime_error("1-St exception. ");
}
catch(...)
{
std::cout << "Catched an error during doSmth. " << std::endl;
};
}
int main() {
doSmth();
}
This program will crash because std::terminate is called when stack unwinding (as now a function exits with an exception).
If you throw an exception when another has not been handled yet, and you let the second exception escape a destructor that was called in process of handling the first exception, then you get a well-defined program termination. –
n. 1.8e9-where's-my-share m.
Your program will crash, but that crash is not UB but well-defined behaviour

C++ uncaught exception in worker thread

Uncaught exception behaves differently for main thread and another std::thread.
here is the test program
#include <thread>
class XXX{
public:
XXX(){std::fprintf(stderr, "XXX ctor\n");}
~XXX(){std::fprintf(stderr, "XXX dtor\n");}
};
void mytest(int i)
{
XXX xtemp;
throw std::runtime_error("Hello, world!");
}
int main(int argc, char *argv[])
{
if(argc == 1) {
mytest(0);
}else{
std::thread th([&]{mytest(0);});
th.join();
}
}
above code (C++11), compiled by GCC 5.4
run without args
XXX ctor
terminate called after throwing an instance of 'std::runtime_error'
what(): Hello, world!
Aborted (core dumped)
run 1 arg:
XXX ctor
XXX dtor
terminate called after throwing an instance of 'std::runtime_error'
what(): Hello, world!
Aborted (core dumped)
So the stack unwind is performed in worker thread but not in main thread, WHY?
I'm asking because I'd like core dump to give useful stack backtrace information in both cases (for uncaught exception).
Thanks in advance!!!
Further trials reveals that add noexcept keyword to thread function body mytest() can partially solves my problem because unwind will fail,but its not a good solution because unwind will still partially happen if mytest() is calling another function without noexcept guarantee and actually thrown the uncaught exception.
Update: Thanks to all comment providers, now I understand C++ exception is not backtrace friendly, and GCC, as a C++ implementation,has the freedom to choose to not unwind when uncaught exception is thrown from main thread, and unwind when from worker thread.
Update: Special thanks to Sid S & Jive Dadson, I must mixed up some concepts: 1) exception/error handling; 2) runtime assertion 3) Segment fault, 2&3 are similar, they are UN-recoverable errors, abort immediately is the only choice, they are also backtrace friendly in debugger because stack unwind is not involved. they should not be implemented using exception concept at all. exception is supposed to be caught always, let uncaught exception leaving main() is not a recommended usage.
Why? That's just the way it is. Since c++11, there is some support for dealing with exceptions thrown in threads other than main, but you will need to instrument the threads to catch exceptions and re-throw them. Here's how.
#include <thread>
#include <iostream>
class XXX {
public:
XXX() { std::fprintf(stderr, "XXX ctor\n"); }
~XXX() { std::fprintf(stderr, "XXX dtor\n"); }
};
void mytest(int i)
{
XXX xtemp;
throw std::runtime_error("Hello, world!");
}
int main(int argc, char *argv[])
{
std::exception_ptr exception_ptr = nullptr;
if (argc == 1) {
mytest(0);
}
else {
std::thread th([&exception_ptr]() {
try {
mytest(0);
}
catch (...) {
exception_ptr = std::current_exception();
}
});
th.join();
if (exception_ptr) {
try {
std::rethrow_exception(exception_ptr);
}
catch (const std::exception &ex)
{
std::cerr << "Thread exited with exception: " << ex.what() << "\n";
}
}
}
}
You should catch the exception in the thread where it occurs. The default handler will call terminate() wherever it is at, unwinding or not depending on implementation.

Should std::current_exception return non-null from catch block in a class's destructor

My coworkers and I think we have found a bug in Visual C++ 2012 and 2013 but we aren't sure. Should the call to std::current_exception in the following code be expected to return a non-null exception_ptr? It seems to on most other compilers we've tried:
#include <exception>
#include <stdexcept>
#include <iostream>
class A
{
public:
~A()
{
try
{
throw std::runtime_error("oh no");
}
catch (std::exception &)
{
std::clog << (bool)std::current_exception() << std::endl;
}
}
};
void foo ()
{
A aa;
throw std::runtime_error("oh no");
}
int main(int argc, char **)
{
try
{
foo();
}
catch(...)
{
}
return 0;
}
When run under Visual C++ we get "0" (false, which means the exception_ptr returned is null). Other compilers, such as g++, print "1".
cppreference says this about std::current_exception:
If called during exception handling (typically, in a catch clause), captures the current exception object and creates an std::exception_ptr that holds either a copy or a reference to that exception object (it is implementation-defined if a copy is made).
If the implementation of this function requires a call to new and the call fails, the returned pointer will hold a reference to an instance of std::bad_alloc
If the implementation of this function requires to copy the captured exception object and its copy constructor throws an exception, the returned pointer will hold a reference to the exception thrown. If the copy constructor of the thrown exception object also throws, the returned pointer may hold a reference to an instance of std::bad_exception to break the endless loop.
If the function is called when no exception is being handled, an empty std::exception_ptr is returned.
Throwing an exception unwind your stack which should call the destructor of your A class on your aa instance, in which you have a simple try/throw/catch bloc of code which catches the exception.
Of course it's not as authoritative as the standard, but it seems to me that g++/clang are right while visual is not (the other way around happens less often :p)
As confirmed by James McNellis, this is definitely a bug. I had the great pleasure of discovering it today.
In your case, the workaround is to call make_exception_ptr instead of current_exception in your handler:
~A()
{
try
{
throw std::runtime_error("oh no");
}
catch (std::exception & e)
{
std::clog << (bool)std::make_exception_ptr(e) << std::endl;
}
}
But I think we are out of luck for catch(...) clauses and a fix is really needed.
Edit1: I reported this bug in "connect" a long time ago. It can now be found on Developper Community.
Edit2: The bug was fixed in VS2019 16.3.

When exactly has an exception been caught?

I get this terminating with uncaught exception even though I thought I had caught the exception. Here is some example code
#include <iostream>
#include <stdexcept>
void throwing(int x)
{
if(x) throw std::runtime_error("x non-null");
}
int main()
{
try {
throwing(1);
} catch(std::runtime_error const&ex) {
std::clog << "error: \"" << ex.what() << '\"' << std::endl;
std::terminate();
}
return 0;
}
which produces (after reporting error: "x non-null") the said message (using clang++ with std=c++11). So, when exactly has the exception been caught and hence deemed uncaught in the sense of terminate() not reporting it (again)? Or, equivalently (or not?): how can I catch an exception, report its what(), and terminate() without getting this blurb?
(I could refrain from reporting the what() and just terminate(), but I want to report the what() in my own way.)
Since noone provided an answer to this, and it seems like my comment was either not clear enough or overlooked, I'll post a full answer:
Or, equivalently (or not?): how can I catch an exception, report its what(), and terminate() without getting this blurb?
If you read carefully thru the reference, you'll notice std::terminate() by default calls abort(), which causes the program to terminate returning a platform-dependent unsuccessful termination error code to the host environment.
Now, answering the quoted question: either use exit(int status) (which is a better solution, since you handled the exception) instead of terminate, or change the terminate handler.

C++ unhandled exceptions

Does C++ offer a way to 'show' something visual if an unhandled exception occurs?
What I want to do is to make something like assert(unhandled exception.msg()) if it actually happens (like in the following sample):
#include <stdexcept>
void foo() {
throw std::runtime_error("Message!");
}
int main() {
foo();
}
I expect this kind of code not to terminate immediately (because exception was unhandled), rather show custom assertion message (Message! actually).
Is that possible?
There's no way specified by the standard to actually display the message of the uncaught exception. However, on many platforms, it is possible anyway. On Windows, you can use SetUnhandledExceptionFilter and pull out the C++ exception information. With g++ (appropriate versions of anyway), the terminate handler can access the uncaught exception with code like:
void terminate_handler()
{
try { throw; }
catch(const std::exception& e) { log(e.what()); }
catch(...) {}
}
and indeed g++'s default terminate handler does something similar to this. You can set the terminate handler with set_terminate.
IN short, no there's no generic C++ way, but there are ways depending on your platform.
Microsoft Visual C++ allows you to hook unhandled C++ exceptions like this. This is standard STL behaviour.
You set a handler via a call to set_terminate. It's recommended that your handler do not very much work, and then terminate the program, but I don't see why you could not signal something via an assert - though you don't have access to the exception that caused the problem.
I think you would benefit from a catch-all statement as follows:
int main() {
try {
foo();
catch (...) {
// Do something with the unhandled exception.
}
}
If you are using Windows, a good library for handling unhandled exceptions and crashes is CrashRpt. If you want to do it manually you can also use the following I wrote in this answer.
If I'm reading your question correctly, you're asking if you can overload throw (changing its default behavior) so it does something user-defined. No, you can't.
Edit: since you're insistent :), here's a bad idea™:
#include <iostream>
#include <stdlib.h>
#include <windows.h>
void monkey() {
throw std::exception("poop!");
}
LONG WINAPI MyUnhandledExceptionFilter(struct _EXCEPTION_POINTERS *lpTopLevelExceptionFilter) {
std::cout << "poop was thrown!" << std::endl;
return EXCEPTION_EXECUTE_HANDLER;
}
int main() {
SetUnhandledExceptionFilter(&MyUnhandledExceptionFilter);
monkey();
return 1;
}
Again, this is a very bad idea, and it's obviously platform-dependent, but it works.
Yes, its possible. Here you go:
#include <iostream>
#include <exception>
void foo()
{
throw std::exception("Message!");
}
int main()
{
try
{
foo();
}
catch (std::exception& e)
{
std::cout << "Got exception: " << e.what() << std::endl;
}
return 0;
}
The c++ standard is the terminate handler - as other have said
If you are after better traceablility for throws then this is what we do
We have a macro Throw that logs the file name and line number and message and then throws. It takes a printf style varargs message.
Throw(proj::FooException, "Fingle %s unable to process bar %d", fingle.c_str(), barNo);
I get a nice log message
Throw FooException from nargle.cpp:42 Fingle barf is unable to process bar 99
If you're really interested in what happened to cause your program to fail, you might benefit from examining the process image in a post-mortem debugger. The precise technique varies a bit from OS to OS, but the basic train is to first enable core dumping, and compile your program with debug symbols on. Once the program crashes, the operating system will copy its memory to disk, and you can then examine the state of the program at the time it crashed.