To have exceptions or not to have exceptions

closed account (S6k9GNh0)
I've never really understood the actual advantage of exceptions (outside of help in the constructor). They seem to be fat and slow, while not being very elegant, and extremely tricky in a threaded environment.

I'm finally creating a small header based library for personal use and I can't figure out whether I should place macros all over the place to check for exception support or not... or perhaps there is a better way?

Also, I swear I made a topic like this before that never got answered...
Last edited on
With so many negative preconceptions (fat, slow, not elegant, tricky), it would be hard to have a helpful discussion about error handling.

Could you take some function from that library and use that to illustrate the question?
I've never really understood the actual advantage of exceptions (outside of help in the constructor).


They let you write code under the assumption that everything is always working. And they let you consolidate all error handling code in a separate body of code.

Really, they greatly simplify the writing of error-aware code.

For example... new throws an exception on bad allocation. This is relied upon by pretty much every container class. Can you imagine what a nightmare it would be if this was replaced with returning error codes? If you had to put every single push_back(), insert(), etc inside of an if statement to check for failure?

And I don't know if you've ever done any DirectX in C++, but it's not exactly what I'd call fun. It's pretty much as bad as you'd expect, where every single function you call has the possibility to error, so you either end up just ignoring errors completely, or every other line is an if(failed) check.

They seem to be fat and slow


Not from my experience. And I'm not convinced they'd really be slower than a million checks for error conditions.

while not being very elegant


They're very elegant. Compare:

1
2
3
4
5
6
7
8
9
10
11
try
{
   DoSomething();
   DoSomethingElse();
   DoSomethingAgain();
   DoSomethingOneLastTime();
}
catch(...)
{
    CleanUp();
}


vs.

1
2
3
4
if(!DoSomething())              {  CleanUp();  return; }
if(!DoSomethingElse())          {  CleanUp();  return; }
if(!DoSomethingAgain())         {  CleanUp();  return; }
if(!DoSomethingOneLastTime())   {  CleanUp();  return; }


(EDIT: pretty printed the non-exception code to be fair)

and extremely tricky in a threaded environment


How so? The only complications that really arise is if an exception occurs in the midst of something you can't have interrupted. And if you're using RAII for everything like you should be... situations like that are few and far between.
Last edited on
Topic archived. No new replies allowed.