Search

15.6 — Exception dangers and downsides

As with almost everything that has benefits, there are some potential downsides to exceptions as well. This article is not meant to be comprehensive, but just to point out some of the major issues that should be considered when using exceptions (or deciding whether to use them).

Cleaning up resources

One of the biggest problems that new programmers run into when using exceptions is the issue of cleaning up resources when an exception occurs. Consider the following example:

What happens if WriteFile() fails and throws a FileException? At this point, we’ve already opened the file, and now control flow jumps to the FileException handler, which prints an error and exits. Note that the file was never closed! This example should be rewritten as follows:

This kind of error often crops up in another form when dealing with dynamically allocated memory:

If ProcessPerson() throws an exception, control flow jumps to the catch handler. As a result, pJohn is never deallocated! This example is a little more tricky than the previous one -- because pJohn is local to the try block, it goes out of scope when the try block exits. That means the exception handler can not access pJohn at all (its been destroyed already), so there’s no way for it to deallocate the memory.

However, there are two relatively easy ways to fix this. First, declare pJohn outside of the try block so it does not go out of scope when the try block exits:

Because pJohn is declared outside the try block, it is accessible both within the try block and the catch handlers. This means the catch handler can do cleanup properly.

The second way is to use a local variable of a class that knows how to cleanup itself when it goes out of scope. The standard library provides a class called std::auto_ptr that can be used for this purpose. std::auto_ptr is a template class that holds a pointer, and deallocates it when it goes out of scope.

Note that std::auto_ptr should not be set to point to arrays. This is because it uses the delete operator to clean up, not the delete[] operator. In fact, there is no array version of std::auto_ptr! It turns out, there isn’t really a need for one. In the standard library, if you want to do dynamically allocated arrays, you’re supposed to use the std::vector class, which will deallocate itself when it goes out of scope.

Exceptions and destructors

Unlike constructors, where throwing exceptions can be a useful way to indicate that object creation succeeded, exceptions should not be thrown in destructors.

The problem occurs when an exception is thrown from a destructor during the stack unwinding process. If that happens, the compiler is put in a situation where it doesn’t know whether to continue the stack unwinding process or handle the new exception. The end result is that your program will be terminated immediately.

Consequently, the best course of action is just to abstain from using exceptions in destructors altogether. Write a message to a log file instead.

Performance concerns

Exceptions do come with a small performance price to pay. They increase the size of your executable, and they will also cause it to run slower due to the additional checking that has to be performed. However, the main performance penalty for exceptions happens when an exception is actually thrown. In this case, the stack must be unwound and an appropriate exception handler found, which is a relatively an expensive operation. Consequently, exception handling should only be used for truly exceptional cases and catastrophic errors.

16.1 -- The Standard Template Library (STL)
Index
15.5 -- Exceptions, classes, and inheritance

13 comments to 15.6 — Exception dangers and downsides

  • Awais Ali

    I just simply loved the tutorial. They are far better than any book and the examples are very good to help one clear his doubts. And I would love to see something on Design Patterns. :)

  • [...] Learn C 15 6 Exception dangers and downsides Posted by root 4 hours ago (http://www.learncpp.com) Comment by daniel 2008 10 26 15 46 54 if pjohn delete pjohn learn c is powered by wordpress using tiga theme with a bit of ozh wp 2 2 2 3 Discuss¬† |¬† Bury |¬† News | Learn C 15 6 Exception dangers and downsides [...]

  • Ashwini

    Thanks Alex!!! I have read your tutorial from start to finish and it has been of immense help to me. I am much more confident in C++ programming now. Hope to see more tutorials from you :-)

  • Stas

    Unlike constructors, where throwing exceptions can be a useful way to indicate that object creation succeeded

    Did you mean "object creation failed" ?

  • Some guy

    Looks like someone's spamming at the Cleaning up resources-chapter on this page :/

    Only appears with Javascripting disabled.

  • Adel

    By far, this is the best and simplest tutorial I have come across. Thanks a lot Alex, it was a pleasure to read. One of the nicest things about it (other than being well written and simple) is that it explains the need behind the various language features before explaining how they work/should be used.

  • bryce

    Thanks Alex!!! I've read your tuts from start to finish, and i've learned a huge amout on C++ programming! now i'm going to move onto some books, i think what i've learned here will become the foundation of my C++ knowledge for me to build on!

    Only thing i could think of is add more exercises....i really missed them in the later chapters.

    Thanks again,
    Bryce

  • Kiena

    Alternatively the 4th example could be written as:

    Person *pJohn = NULL;
    try
    {
        pJohn = new Person("John", 18, E_MALE);
        ProcessPerson(pJohn );
    }
    catch (PersonException &cException)
    {
        cerr << "Failed to process person: " << cException.what() << endl;
    }
    delete pJohn;
    

    Like this the cleanup code appears only once.

    This is similar to the "finally" manner in other languages, except in c++ it still won't be executed when a non-handled kind of exception occurs, which applies to the original code too.

  • STEPHEN L.

    Looks like the end of the road bye and thx for the great tuts.

  • if (pJohn)
        delete pJohn;

    I think that could and should be just

    delete pJohn;

    Thanks again for the great tutorials,
    ~Daniel

    [ Old habits die hard. Thanks! -Alex ]

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">