Terminate Called After Throwing Fix
Written November 28, 2026 · Tested with GCC 13.3.0 · 7 min read
- The failure: an exception escapes main
- Fix for the plain case: catch it in main
- A handler in the caller does not save a noexcept function
- An exception cannot cross from one thread to another
Written November 28, 2026
Tested with GCC 13.3.0
What this guide is
This message is not a compile error. The program built, started, and then died at run time:
terminate called after throwing an instance of 'std::invalid_argument'
what(): stoi
The two lines mean an exception was thrown and no handler caught it, so the runtime called std::terminate, and the default terminate handler called std::abort. The shell reports the program as aborted, and its exit status is 134. There is no return from this: no later statement in the program runs, and no handler written somewhere else in the program gets a second chance.
The fix is never at the point where the message appears. By then the exception is already uncatchable in that context. The fix is to catch the exception earlier, in a context where a handler is allowed to run, or to stop the throw from escaping a context that forbids it. This guide shows the routes that produce the message — an uncaught throw out of main, a throw out of a noexcept function, a throw out of a thread function, a throw out of a destructor during unwinding, and a direct call to std::terminate — and the catch that fixes each one. The type named in the first line and the text after what(): change from case to case, and both are read below.
Build every program in this guide with g++ -std=c++20 -g.
The failure: an exception escapes main
The smallest form needs no throw statement of its own. std::stoi throws std::invalid_argument when its argument is not a number, and this program has no handler anywhere:
#include <string>
int main() {
int n = std::stoi("abc");
return n;
}
$ g++ -std=c++20 -g -o uncaught uncaught.cpp
$ ./uncaught
terminate called after throwing an instance of 'std::invalid_argument'
what(): stoi
Read the two lines in order. The first names the dynamic type of the exception that was in flight, std::invalid_argument. The second is that exception's what() text, here the short string stoi, naming the function that threw. Neither line is printed by the program. Both come from the runtime after the handler search failed: the exception left main, there was no caller above main to offer it to, std::terminate was called, and the default handler aborted the process.
Fix for the plain case: catch it in main
The same call inside a try block, with a handler for the type the first line named, runs clean:
#include <iostream>
#include <string>
int main() {
try {
int n = std::stoi("abc");
std::cout << n << "\n";
} catch (const std::invalid_argument& e) {
std::cout << "caught: " << e.what() << "\n";
}
std::cout << "program continues\n";
return 0;
}
$ g++ -std=c++20 -g -o caught caught.cpp
$ ./caught
caught: stoi
program continues
The handler prints the same text the terminate message carried after what():, because it is reading the same exception object through e.what(). The difference is only where the exception stopped. Caught, it is information the program can act on — substitute a value, ask again, or report the input and exit normally. Uncaught, the same information is the last thing the runtime prints before the abort. When the input can be bad, the choices are this handler or checking the input before the call; letting the throw reach the top of main is not a third choice, it is the failure above.
A handler in the caller does not save a noexcept function
A function marked noexcept promises that no exception will leave it, and the promise is enforced at run time, not by catching. This program has a handler in main, written correctly around the call, and it never runs:
#include <iostream>
#include <stdexcept>
void work() noexcept {
throw std::runtime_error("boom from noexcept");
}
int main() {
try {
work();
} catch (const std::exception& e) {
std::cout << "caught in main: " << e.what() << "\n";
}
std::cout << "program continues\n";
return 0;
}
GCC warns about this one at build time, before it ever runs:
$ g++ -std=c++20 -g -o noexcept_escape noexcept_escape.cpp
noexcept_escape.cpp: In function 'void work()':
noexcept_escape.cpp:4:5: warning: 'throw' will always call 'terminate' [-Wterminate]
4 | throw std::runtime_error("boom from noexcept");
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$ ./noexcept_escape
terminate called after throwing an instance of 'std::runtime_error'
what(): boom from noexcept
The handler in main matches the exception type, and it is still bypassed. When the handler search reaches the boundary of a noexcept function, std::terminate is called there instead of letting the exception cross. The exception never reaches main at all. The fixes are inside the boundary: handle the failure inside work so nothing throws out of it, or remove noexcept from a function that can in fact throw. Adding more handlers in callers changes nothing, and that is the diagnostic value of this case — if the terminate message appears and a matching handler visibly exists in a caller, look for a noexcept boundary between the throw and that handler.
An exception cannot cross from one thread to another
A handler in main does not reach into a thread either. If the function a std::thread runs lets an exception escape, std::terminate is called, even though main is still waiting at join:
#include <stdexcept>
#include <thread>
void run() {
throw std::runtime_error("Thread failure");
}
int main() {
std::thread t{run};
t.join();
return 0;
}
$ g++ -std=c++20 -g -o thread_escape thread_escape.cpp
$ ./thread_escape
terminate called after throwing an instance of 'std::runtime_error'
what(): Thread failure
The top-level function of a thread is a boundary like the top of main: there is no caller on that thread to catch anything. The fix is to catch inside the thread function, where the exception is still on its own thread:
#include <iostream>
#include <stdexcept>
#include <thread>
void run() {
try {
throw std::runtime_error("Thread failure");
} catch (const std::exception& e) {
std::cout << "caught in thread: " << e.what() << "\n";
}
}
int main() {
std::thread t{run};
t.join();
std::cout << "program continues\n";
return 0;
}
$ g++ -std=c++20 -g -o thread_caught thread_caught.cpp
$ ./thread_caught
caught in thread: Thread failure
program continues
A thread function that can fail should catch at its own top level as a matter of shape, and carry the result back to the joining code through a variable, a future, or another channel the program defines. The exception itself cannot make that trip.
A destructor throwing during unwinding ends the program
While an exception is in flight, the objects in the scopes it leaves are destroyed. If one of those destructors throws, the runtime would be holding two live exceptions, and it terminates instead. This program's Guard destructor is declared noexcept(false) so the throw is allowed to leave it at all, and it throws while the original exception is unwinding through the try block:
#include <iostream>
#include <stdexcept>
struct Guard {
~Guard() noexcept(false) {
throw std::runtime_error("from destructor");
}
};
int main() {
try {
Guard g;
throw std::runtime_error("original");
} catch (const std::exception& e) {
std::cout << "caught: " << e.what() << "\n";
}
return 0;
}
$ g++ -std=c++20 -g -o dtor_unwind dtor_unwind.cpp
$ ./dtor_unwind
terminate called after throwing an instance of 'std::runtime_error'
what(): from destructor
The handler in main matches, and it never runs. The what(): text is the destructor's message, not the original exception's, because the destructor's throw is the one that triggered terminate. In ordinary code the case is stricter than this example: destructors are implicitly noexcept unless declared otherwise, so a throw escaping a normal destructor calls std::terminate even when no other exception is in flight. The working rule is the same in both forms: a destructor does its cleanup without throwing, and when cleanup can fail, the destructor records or ignores the failure and leaves the reporting to a named function a caller can invoke while a handler is available.
The type and the what(): text change with the exception
The first line names whatever type was thrown, and the second line is that type's what() text, so the pair identifies the throw even when the program prints nothing of its own. A checked container access that nobody catches produces a different pair from the same two-line shape:
#include <vector>
int main() {
std::vector<int> v{1, 2};
return v.at(5);
}
$ g++ -std=c++20 -g -o at_uncaught at_uncaught.cpp
$ ./at_uncaught
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 5) >= this->size() (which is 2)
Here the type is std::out_of_range, and the what(): text carries the index that failed, 5, and the size it was checked against, 2. Read together, the two lines usually name the operation that threw and the value that made it throw, which is enough to find the call site before adding the handler around it — a catch for std::out_of_range at the code that supplies the index, or a check of the index against the size before the .at() call.
A custom terminate handler replaces the default message
std::set_terminate installs a different handler for the moment std::terminate is called. The handler must not return; this one prints its own line and calls std::abort itself:
#include <cstdlib>
#include <exception>
#include <iostream>
#include <stdexcept>
int main() {
std::set_terminate([]() {
std::cout << "custom terminate handler\n" << std::flush;
std::abort();
});
throw std::runtime_error("unhandled");
}
$ g++ -std=c++20 -g -o set_terminate set_terminate.cpp
$ ./set_terminate
custom terminate handler
The two runtime lines are gone, replaced by the handler's own output, and the program still aborts with the same exit status, 134. A custom handler is a last-resort reporting hook — a place to log that the program is dying and, using std::current_exception inside the handler, what it is dying of. It is not a recovery mechanism: the handler cannot resume the program, and installing one does not fix any of the routes above. Fix the missing catch first; add a handler only so that a failure that still escapes somewhere leaves a record.
Calling std::terminate directly prints a different first line
Not every terminate message follows a throw. A direct call with no exception in flight names that instead:
#include <exception>
int main() {
std::terminate();
}
$ g++ -std=c++20 -g -o direct_terminate direct_terminate.cpp
$ ./direct_terminate
terminate called without an active exception
When the first line says without an active exception, there is no throw to hunt for. Something in the program, or in a library it calls, invoked std::terminate — or invoked a mechanism that ends there, such as destroying a joinable std::thread — and the search is for that call, not for a missing handler.
The cases, in short
| Case | Handler present | Result |
|---|---|---|
| Throw escapes main | None | Terminate, type and what(): printed |
| Throw caught in main | Matching handler in main | Handler runs, program continues |
| Throw escapes a noexcept function | Matching handler in caller | Terminate, handler bypassed |
| Throw escapes a thread function | None on that thread | Terminate |
| Throw caught inside the thread function | Handler on same thread | Handler runs, program continues |
| Destructor throws during unwinding | Matching handler in main | Terminate, what(): is the destructor's |
| Custom handler installed with std::set_terminate | None | Handler's own output, still aborts |
| std::terminate called directly | No exception in flight | 'terminate called without an active exception' |
The fixes, ranked
- Catch the exception in the context where it is thrown: in main for a throw out of main, inside the thread function for a throw on a thread. The handler must be on the same side of every boundary the exception would have to cross.
- Keep noexcept honest: a function that can throw either handles every failure inside itself or loses the noexcept marking. A caller's handler cannot substitute.
- Never let a destructor throw. Do the cleanup, record failures, and report them from a named function instead.
- Read the two lines before changing anything: the type and the what(): text name the throw, and the without an active exception variant points at a direct terminate instead.
- Install a custom terminate handler only as a reporting hook for failures that still escape, never as the fix.
Checklist
- Read the first line: after throwing an instance of names the exception type; without an active exception means no throw was involved.
- Read the what(): line: it is the exception's own message, and it often names the operation and the offending value.
- Find the boundary the exception died at: top of main, a noexcept function, a thread function, or a destructor during unwinding.
- Check for a noexcept function between the throw and any existing handler before adding another handler.
- Move the catch to the throwing side of the boundary: into main, into the thread function, or inside the noexcept function.
- Keep destructors non-throwing, including during unwinding.
- Treat a custom terminate handler as logging, not recovery.
Related guides
- C++ Exceptions: try, catch, and throw — the throwing and catching mechanics this guide builds on: handler matching, catch by const reference, and the catch-all form.
- C++23 std::expected Error-Handling Pipelines — the other error channel: failures carried in return values, for code that should not throw across these boundaries at all.
- C++ Classes and Objects — the class basics behind the destructor case: members, member functions, and destructors.
Sources
- cppreference, std::terminate — std::terminate is called when an exception is thrown and not caught, when a noexcept specification is violated, when an exception is thrown from the initial function of a std::thread, and in the other listed cases; it calls the currently installed terminate handler, and the default handler calls std::abort.
- cppreference, std::set_terminate — set_terminate makes its argument the new global terminate handler and returns the previously installed one; the handler must terminate execution without returning to its caller, and inside it std::current_exception can recover the exception that led there.
- cppreference, noexcept specifier — when the search for a handler encounters the outermost block of a non-throwing function, std::terminate is called; a noexcept specification is not a compile-time check that the function body cannot throw.
- cppreference, std::thread — if the top-level function of a thread terminates by throwing an exception, std::terminate is called.
Keep Exploring
Seven tips and seven puzzles so far, each one a short runnable example with the fix explained.
Paste an AddressSanitizer, UBSan, or ThreadSanitizer report and get the bug, the file and line, and the fix \u2014 in plain language.
C++20 and C++23 features, migration paths, and measured trade-offs.
The full C++ hub \u2014 language basics, the standard library, coroutines, and measured comparisons.
Paste a [Service] section and get a plain-language verdict on every sandboxing setting it finds.