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.