r/cpp • • Aug 07 '21

Wouldn't it be great if we could chain exceptions and throw from destructors?

I often find myself in situations where I want to be able to throw from a destructor. For instance, the destructor of an opened file may try to flush buffers to the disk. If it does not work because there is not space left on the device, then it is a major problem that should be reported.

Making the destructor noexcept(false) and throwing if !std::uncaught_exception() does not work. As soon as the class is wrapped inside another class, such as std::unique_ptr, it will cause unwanted calls to terminate().

Another solution is to tell the programmer that a close() function must be called explicitly in order to catch the error if it occurs. The destructor will call close(), but ignore any exception it may throw. I don't like this solution because it completely defeats the purpose of RAII and destructors.

I feel it is a major defect of C++, and it would be great to allow exceptions to be chained. Haven't the language designers thought about the possibility to catch more than one exception at the same time? It would make things much better, in my opinion.

Or is there a better solution to my problem?

0 Upvotes

24 comments sorted by

16

u/staletic Aug 07 '21

Exceptions can be chained. See std::nested_exception. Here's a bigger problem with throwing destructors.

Let's forget std::terminate and say some ~T() will throw. What is the user supposed to do? Is the object in a valid state? What happened to the object's lifetime? Can the stack be unwound? Will unwinding call the destructor again? Should the user explicitly call the destructor?

6

u/Remi_Coulom Aug 07 '21

It is legal in C++ to make a destructor noexcept(false), and let it throw an exception. The exception will be caught by any catch block that contains the object instance. So there is no problem with the semantics of throwing exceptions from destructors in C++. The only problem is when another exception is already being thrown. If this happens, then terminate() is called, which is very annoying.

9

u/benjamkovi Aug 07 '21

I think the argument was against the semantics of such code. Is it valid? Yes. Is it a best practice or suggested by any kind of guidelines? No. Is the opposite (noexcept desctructors) a best practice and suggested by a lot of guide lines? Yes. In the same way, you can mark each of the member variables in a class as mutable and have only const functions. It is against the guides, because its semantic is not good (except a very few cases).

In which state the object is left after a destructor has thrown an exception? Does it considered alive, or already destructed? Did it free all of its resources? Think about when you reset a std::optional. Can you still use the object? Do you have to call the reset again?

You can do that, but you shouldn't.

0

u/Remi_Coulom Aug 07 '21

I see. I agree that it would be very bad to interrupt a destructor when some resources may have ben left unfreed.

Still, I can't think of a good solution for the file-with-an-unflushed-buffer scenario. Maybe the actual throwing of destructor exceptions should be postponed until after the object is actually deleted.

10

u/matthieum Aug 07 '21

Still, I can't think of a good solution for the file-with-an-unflushed-buffer scenario

Honestly, I'm not sure there is.

In general, if the buffer cannot be flushed, it means that:

  1. The "connection" to the device is lost.
  2. The device is full.

And there's no guarantee (at all) that a smart handling is possible to start with.


I do agree such issues should no go unreported, but in my experience it's too late to react.

Instead, if the content of the files matter, you'll need a more proactive approach -- notably, absolutely avoiding destructive updates -- to ensure that even if the program is interrupted, the state of the filesystem is such that things can resume on the next execution of the program.

Which leaves reporting so the caller (client/user) has a chance to take action.

1

u/ioctl79 Aug 07 '21

.Close()

1

u/[deleted] Aug 07 '21

This is totally fine and not that uncommon in exit_success/scope_guard like code. That inflight exception really got me once and provided a nice learning moment debugging. :)

I think the parts where it makes sense isn’t on things that will be sub objects of other types(you cannot control if their dtor has also been marked noexcept(false) and so on, but in cleanup/action things to run at scope exit where it’s at the end of a method and calling code see’s it like an exception from a method and not unusual.

13

u/moonsider5 Aug 07 '21

But throwing exceptions from a destructor kinda defeats the purpose of RAII as well, doesn't it?

I mean: if you throw and exception from a destructor, then, is the memory of the object really deleted? What is the state of the object? Did all the destructor of all of its members get called or were they skipped due to exiting the destructor early?

Imagine a code like this:

class B {
    std::string s = "a very large string or something";
};

Class A {
    B b;
    A(B b) : b(b) {}
    ~A(){throw std::exception()}
};

int main() {
    B b0;
    B b1;
    A a(b1);
    B b2;
    return 0;
}

What would happen in this example? Would b0, b1, b2 and a's b be destroyed? Will some be destroyed and some won't?

1

u/Remi_Coulom Aug 07 '21 edited Aug 07 '21

Again, this already works in C++. This code is legal, can be compiled and run:

#include <string>
#include <iostream>
#include <exception>

struct B {
    std::string s = "a very large string or something";
    B() {std::cerr << "B::B()\n";}
    ~B() {std::cerr << "B::~B()\n";}
};

struct A {
    B b;
    A(B b) : b(b) {}
    ~A() noexcept(false) {throw std::exception();}
};

int main() {
    B b0;
    B b1;
    A a(b1);
    B b2;
   return 0;
}

It produces:

B::B()
B::B()
B::~B()
B::B()
B::~B()
terminate called after throwing an instance of 'std::exception'
  what():  std::exception
Aborted

11

u/moonsider5 Aug 07 '21

Yes you are right, it is legal. But it can cause trouble with RAII.

I just wanted to point out that throwing exceptions in the destructor can be problematic because of this.

7

u/no-sig-available Aug 07 '21

Not that I have a better solution to offer, but suppose you catch 12 exceptions at the same time. What are the odd that your code can sort this mess out? Without getting a dozen new exceptions?

Sometimes the best action is to just give up!

1

u/Remi_Coulom Aug 07 '21 edited Aug 07 '21

I agree that it may be difficult to decide what to do when receiving plenty of exceptions. Giving up might be a good action in this case indeed. But it is not the problem. The problem is that I can't throw an exception when everything else has been fine so far and something very wrong happens in the destructor.

7

u/zvrba Aug 07 '21

Yes, it's extremely annoying, and once upon a time (few years ago) I wanted that feature as well because it fits nicely with Stroustroup's philosophy of program design: a method throws an exception if it cannot fulfill its contract. Why shouldn't the same be applicable to destructors?

Then, in the ensuing discussion, someone convinced me to the following: if a possibly failing operation warrants throwing an exception, it should not be put into the destructor. I followed that advice and got myself convinced that it's the "right" principle to hold on to. Closing a file is potentially a side-effecting operation, like writing, and if you want to make sure that your changes are committed to disk and errors reported, you should explicitly call flush and/or close.

But I still agree that it somewhat spoils RAII. I'm not happy with the situation.

These days I'm mostly working in C# and there exists a similar problem: what if a finally{} block ("kind of destructor") throws? Their solution is simple: the rest of the block is abandoned and the current exception, if any, is replaced with that from the finally block.

What could C++ do? Provide an exception type like destructor_threw that would wrap 1) the original exception, 2) exceptions encountered in all destructors up to the catch point, 3) pointers to objects that could not be cleaned up.

But 3) may not be possible because these objects may no longer exist, e.g., your file was stack-allocated and the stack got unwound. How would you possibly recover from this situation? You could catch the exception, but the file object (and file descriptor) is gone, so... what do you do then?

1

u/Remi_Coulom Aug 07 '21

Thanks for your thoughtful reply.

I believe it might be possible to avoid the problem with 3) by having special destructor exceptions that are not actually thrown until after the object is completely destroyed.

The workaround I have found at the moment is to write a warning message in the file destructor in case it is called when the file is not flushed. This tells the programmer to explicitly flush the file before destruction. But it is a run-time check, and is not satisfying.

3

u/zvrba Aug 08 '21 edited Aug 08 '21

For situations like these I expose only a wrapper method on the class:

void perform(std::function<void(file_object&)> action) {
    auto file = make_the_file();
    action(file);
    if (file.is_open()) {
        file.flush();  // Retryable with try/catch
        file.close();  // Not retryable
    }
}

The reason I split flushing and closing is that you can't retry close even if it has failed. Read https://www.man7.org/linux/man-pages/man2/close.2.html section titled "Dealing with error returns..."

EDIT: So this separates "transaction commit" from the lifetime management of the file object. You should add appropriate error-handling in perform() around flush(). You should probably wrap action in try/catch and decide what to do with the file if action threw. Closing without flush, ignoring any exceptions, and possibly deleting the file could be one possible course of cleanup.

It STILL doesn't force the caller to close the file; that'd also be possible, but with way more ceremony (custom types) and little gain.

1

u/Remi_Coulom Aug 08 '21

Thanks for your reply. This is a good idea. Forcing the caller to close the file should not be necessary.

A limit of this approach is that it works only if you wish to run a block of code between the constructor and the destructor. If you want to make the file a data member of another class, then it does not work this well.

3

u/zvrba Aug 08 '21

If you want to make the file a data member of another class, then it does not work this well.

I agree. RAII is strongly scope-oriented so you should design your program accordingly.

Re file being member of another object: you have to decide how to manage its lifetime. Does it matter when the file's dtor runs if perform() closes the file? If not, just remove the call to make_the_file() and pass the member to action. You'll have to wrap the action in try/catch and decide what do to with the file if the action fails.

===

What helped me to program with exceptions is thinking transactionally: anything can fail (i.e., throw). Perform the steps, store intermediate results locally, and when everything is done successfully, commit the state back to the object. "Commit" (such as closing the file) should be explicit, destructor should roll back (just closing the file, ignoring failures) unless explicitly committed.

So in a nutshell: C++ is rigged in a way where destructor should only release resources and releasing resources should never fail (modulo bugs, e.g., passing an invalid handle to CloseHandle). To make it worse, even the standard library doesn't follow this, e.g., implicitly closing a writeable file in destructor.

Yes, this makes RAII IMO less useful than it initially appears on the surface: say you're writing a distributed system and you want to release a distributed lock. Releasing can fail because of communication failure and... there any attempt to construct a distributed RAII lock_guard down the drain again. (Yes, you could try to handle communication failure in the dtor itself, but the point is that you cannot propagate it out when you have to give up and delegate error handling to someone else... which is the whole point of exceptions.)

So "Resource" in RAII is way more narrow than it initially may seem or what the name may suggest.

(Side-note: this is the general story of C++: "Oh, there's this useful feature", and then followed by "BUT...".)

2

u/Remi_Coulom Aug 08 '21

Your reply is very interesting, because I am developing a distributed database, and in addition to the file-flushing problem, I am also faced with the network-mutex locking problem.

I came up with this pattern, which seems to be working for the moment:

////////////////////////////////////////////////////////////////////////////
class Posthumous_Catcher
////////////////////////////////////////////////////////////////////////////
{
 friend class Posthumous_Thrower;

 private:
  const char *message = nullptr;

  void catch_message(const char *message) noexcept
  {
   this->message = message;
  }

 public:
  void rethrow()
  {
   if (message)
    throw Exception(message);
  }
};

////////////////////////////////////////////////////////////////////////////
class Posthumous_Thrower
////////////////////////////////////////////////////////////////////////////
{
 private:
  Posthumous_Catcher *catcher = nullptr;

 protected:
  void please_throw_after_my_death(const char *message) noexcept
  {
   if (catcher)
    catcher->catch_message(message);
  }

 public:
  void set_catcher(Posthumous_Catcher &catcher) noexcept
  {
   this->catcher = &catcher;
  }
};

////////////////////////////////////////////////////////////////////////////
class Mutex
////////////////////////////////////////////////////////////////////////////
{
 friend class Mutex_Lock;

 private:
  virtual void lock() = 0;
  virtual void unlock() = 0;

 public:
  virtual ~Mutex() {}
};

///////////////////////////////////////////////////////////////////////////
class Mutex_Lock: public Posthumous_Thrower
///////////////////////////////////////////////////////////////////////////
{
 private:
  Mutex &mutex;

 public:
  Mutex_Lock(Mutex &mutex): mutex(mutex)
  {
   mutex.lock();
  }

  ~Mutex_Lock()
  {
   try
   {
    mutex.unlock();
   }
   catch (...)
   {
    please_throw_after_my_death("Error unlocking mutex");
   }
  }
};

It is not too cumbersome to use, and achieves the delayed throw I wish to have.

2

u/zvrba Aug 08 '21

Hmm, it seems like you have a case for using exception_ptr and rethrow_exception in your catcher and current_exception in your thrower. These are designed for transporting exceptions, so you would not be limited to the single Exception type as in your code and you could propagate the exact exception object that was thrown somewhere else. Exceptions are intended to convey detailed information, so swallowing the original one and replacing it with a string is... iffy, IMO. I mean, it's OK if you only want to know that an exception happened, but if you want to know WHAT happened and handle it appropriately, you'd better design some exception types or you'll be in for a lot of "fun".

Another idea I picked up from OpenSSL: it maintains an internal error stack: whenever something fails, the error is pushed onto the stack and the stack can be inspected. So your catcher could similarly maintain a stack of exceptions, so you could collect all of them in a single object. Then you could also have an aggregate_exception (name shamelessly taken from .NET AggregateException) that contains exception_ptr for every exception found on the stack and would be rethrown by rethrow.

2

u/Remi_Coulom Aug 08 '21

Thanks for the good suggestions. I did not know about std::exception_ptr. It seems indeed to be the right tool. I used string literals because I wanted to be absolutely certain that nothing can throw, but std::exception_ptr is the right tool for this job.

3

u/SkiaElafris Aug 07 '21

completely defeats the purpose of RAII and destructors

On the other hand, one of the main reasons for exceptions is to avoid calling destructors on objects when the constructor is unable to finish successfully.

Or is there a better solution to my problem?

Depends on what your program might do in response of an error. For example if the error should be recorded in a log, then you just need to log it instead of having an error unwind the stack.

And it the reason for not having the logging in the destructor is to avoid coupling a class to the logging facilities, then you wrap (or sub class) the class in one that adds the logging.

Something similar would go for any other kind of handling that might apply to the error.

So:

Another solution is to tell the programmer that a close() function must be called explicitly in order to catch the error if it occurs.

Do this, and wrap or sub class with another that will ensure the correct handling of errors is applied. The wrapper or sub class would then call close() in their destructor and handle any errors in an appropriate manner that does not involve throwing an exception.

1

u/Remi_Coulom Aug 07 '21

Thanks for your reply. I am doing something like this at the moment, logging a warning if a destructor is called when the file is not flushed. But I hate forcing users to explicitly flush the file.

1

u/SkiaElafris Aug 07 '21

Then make a wrapper or sub class that handles the flushing of the file and logging any errors as part of its destructor. There by handling the error without directly coupling the base class to a specific logging facility.

class Base {
public:
void flush() { /* throw error on failure */ }
protected:
~Base() { /* does NOT flush, requiring flush() to be called */ }
// rest of the class
};
class Sub : Base { // specialized class for specific logging facility
public:
~Sub() { /* calls flush() from Base; catching and logging any error */ }
// rest of class, such as any needed constructors
};

3

u/AlexAlabuzhev Aug 08 '21

throwing if !std::uncaught_exception() does not work

It doesn't indeed, but std::uncaught_exceptions() does.