0

while writting some C++ code i got to a point, where a certain structure needs an end() function call, to guarantee that the destruction is not throwing any exceptions.

Foo a(x,y)

~a -> may throw under certain really bad circumstances

Foo a(x,y)

a.end() -> maybe throws

~a gurantees to not throw an exception

I wonder if there is an elegant way to force this constraint (end must be called before Deconstruction) by the compiler or at least print out a warning?

Greetings and thanks

user207421
  • 305,947
  • 44
  • 307
  • 483
  • 5
    destructor should never throws exceptions... – ForEveR Feb 27 '13 at 12:33
  • but wouldnt a wrapper just move the problem? The wrapper destructor would call end, but end can throw, therefore the same problem. I could use a try catch, but thats not very elegant in my opinion – Christopher Schildt Feb 27 '13 at 12:37
  • the question is: who will handle this exception? If someone will, let him call it. – kassak Feb 27 '13 at 12:39
  • 1
    Actually, @OliCharlesworth's recommendation is the best approach. Ignore my previous comment.. – Nim Feb 27 '13 at 12:39
  • @ChristopherSchildt: It's not common to run into situations where finalizers throw exceptions, what did you find? – Mooing Duck Feb 27 '13 at 23:28

1 Answers1

4

If you need stuff to occur as a prerequisite of destruction, then you should enforce that by calling it from the destructor.

But you must catch any exceptions, and not let them leak from the destructor.

Community
  • 1
  • 1
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680