Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminate called after throwing an instance of an exception, core dumped

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?

like image 668
HectorJ Avatar asked Jan 02 '19 18:01

HectorJ


People also ask

What is terminate called after throwing an instance of std :: Bad_alloc what (): std :: Bad_alloc?

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.

Does throwing an exception terminate the program?

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.

What to do after throwing an exception?

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.


1 Answers

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.

like image 92
François Andrieux Avatar answered Sep 16 '22 15:09

François Andrieux