'Unhandled exception "terminate called after throwing an instance of" overwrites last line of console
If you throw an unhandled exception out of main like this:
#include <stdexcept>
#include <iostream>
int main()
{
std::cout << "Hello World 1" << std::endl;
throw new std::invalid_argument("A");
return 0;
}
... then the process will terminate with the message "terminate called after throwing an instance of 'std::invalid_argument*'".
You will actually see this on the console:
Hello World 1
terminate called after throwing an instance of 'std::invalid_argument*'
If you print some more text without std::endl and then throw the exception:
#include <stdexcept>
#include <iostream>
int main()
{
std::cout << "Hello World 1" << std::endl;
std::cout << "Hello World 2";
throw new std::invalid_argument("A");
return 0;
}
... then you won't see the second line on the console:
Hello World 1
terminate called after throwing an instance of 'std::invalid_argument*'
It seems that this error message overwrites the last line, e.g. by printing \r before it.
How can this behavior be fixed?
Solution 1:[1]
The second line is not actually overwritten by the message, it never reaches the console!
The problem is that std::cout buffers its output and that this buffer is not flushed if the process terminates. (The error message is actually printed to standard error, not standard output.) And that problem was already discovered:
Is it possible to make std::cout flush automatically before program termination in various failure cases (e.g., exception)
In my case I used this to forcefully flush the buffer:
std::terminate_handler oldTerminateHandler;
void newTerminateHandler()
{
std::cout << std::endl;
if (oldTerminateHandler != nullptr)
{
oldTerminateHandler();
}
}
int main()
{
oldTerminateHandler = std::set_terminate(&newTerminateHandler);
//...
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Niko O |
