Raise exceptions when headers have been sent

Rebase and cleanup of #3998.