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

  • A+
Category:Languages

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?

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: