I am going over C++ exceptions and am running into an error that I am unsure of why it is giving me issues:
#include <iostream>
#include <exception>
class err : public std::exception
{
public:
const char* what() const noexcept { return "error"; }
};
void f() throw()
{
throw err();
}
int main()
{
try
{
f();
}
catch (const err& e)
{
std::cout << e.what() << std::endl;
}
}
When I run it, I get the following runtime error:
terminate called after throwing an instance of 'err'
what(): error
Aborted (core dumped)
If I move the try/catch
logic completely to f()
, i.e.
void f()
{
try
{
throw err();
}
catch (const err& e)
{
std::cout << e.what() << std::endl;
}
}
And just call it from main
(without the try/catch block in main), then there is no error. Am I not understanding something, as it relates to throwing exceptions from functions?
Terminate Called After Throwing an Instance of 'Std::bad_alloc': Solution. A terminate called after throwing an instance of 'std::bad_alloc' is a memory-related error in a programming language C++. What causes the error is a difficult one to track down because it depends on many factors.
We can throw either checked or unchecked exceptions. The throws keyword allows the compiler to help you write code that handles this type of error, but it does not prevent the abnormal termination of the program.
After throwing an exception, you do not need to return because throw returns for you. Throwing will bubble up the call stack to the next exception handler so returning is not required.
The throw()
in void f() throw()
is a dynamic exception specification and is deprecated since c++11. It's was supposed to be used to list the exceptions a function could throw. An empty specification (throw()
) means there are no exceptions that your function could throw. Trying to throw an exception from such a function calls std::unexpected
which, by default, terminates.
Since c++11 the preferred way of specifying that a function cannot throw is to use noexcept
. For example void f() noexcept
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With