Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception handling before and after main

Is it possible to handle exceptions in these scenarios:

  1. thrown from constructor before entering main()
  2. thrown from destructor after leaving main()
like image 246
shiouming Avatar asked Jan 08 '10 08:01

shiouming


People also ask

What are the two basic models in the exception-handling theory?

There are two basic models in exception-handling theory: termination and resumption.


1 Answers

  1. You can wrap up your constructor withing a try-catch inside of it.
  2. No, you should never allow exception throwing in a destructor.

The funny less-known feature of how to embed try-catch in a constructor:

object::object( int param )
try
  : optional( initialization )
{
   // ...
}
catch(...)
{
   // ...
}

Yes, this is valid C++. The added benefit here is the fact that the try will catch exceptions thrown by the constructors of the data members of the class, even if they're not mentioned in the ctor initializer or there is no ctor initializer:

struct Throws {
  int answer;
  Throws() : answer(((throw std::runtime_error("whoosh!")), 42)) {}
};

struct Contains {
  Throws baseball;
  Contains() try {} catch (std::exception& e) { std::cerr << e.what() << '\n'; }
};
like image 54
Kornel Kisielewicz Avatar answered Sep 21 '22 07:09

Kornel Kisielewicz