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::unique_ptr that can be used for this purpose. std::unique_ptr is a template class that holds a pointer, and deallocates it when it goes out of scope.

Exceptions and destructors

Unlike constructors, where throwing exceptions can be a useful way to indicate that object creation did not succeed, exceptions should never 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 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

26 comments to 15.6 — Exception dangers and downsides

  • I think that could and should be just

    Thanks again for the great tutorials,
    ~Daniel

    [ Old habits die hard. Thanks! -Alex ]

  • STEPHEN L.

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

  • Kiena

    Alternatively the 4th example could be written as:

    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.

  • 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

  • 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.

  • Some guy

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

    Only appears with Javascripting disabled.

  • Stas

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

    Did you mean “object creation failed” ?

  • 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 🙂

  • […] 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 […]

  • 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. 🙂

  • Kiran C K

    Under Exceptions and destructors , in the line below:

    "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"

    Isn’t handling the exception the end of the stack unwinding process? It handles the exception after unwinding the stack, right? I did not get the line that the compiler will put in a situation where it doesn’t know whether to continue the stack unwinding process or handle the new exception.

    Let me put it this way, why does both happen at the same time, when exceptions are thrown in destructors?

    • Alex

      When an exception is thrown, the stack is unwound until a handler is found (or until everything has been popped off the stack).

      Assume an exception has been thrown, and in the process of unwinding the stack, a new exception is thrown. At this point, the compiler could reasonably say, “I still haven’t found a handler for my original exception, so I’m going to ignore this one and continue looking for a handler”. This isn’t great because the new exception will never get handled. Alternatively, the compiler could reasonably say, “This new exception is newer, so I’m going to look for a handler for it instead”. This isn’t great because the original exception will never get handled.

      Because of this, throwing an exception while another exception is being handled will cause the program to abort.

      • Kiran C K

        Got that, Alex. Still if no exceptions are used in the code, can we still use exceptions in destructors? I know, there would not be any known purpose for that. I am just asking out of curiosity.

  • Inc

    Remove the references to std::auto_ptr and replace them with std::unqiue_ptr, please!

  • Lokesh

    "Unlike constructors, where throwing exceptions can be a useful way to indicate that object creation succeeded," -> "object creation did not succeed" makes better sense.

  • Darren

    What when we’ve dynamically allocated memory **within** a function say that then throws an exception before deleting the allocation, and the try-catch block is in the calling environment? For example:

    The pointer is not in the scope of the catch block so we cannot delete it’s contents. For this simple example this is not an issue as main terminates after the exception is caught however for a larger program it would be a memory leak if the program continues to run.

    Just thought of the solution. Typically we’re using a conditional to check the state of some variable or other and if that conditional evaluates to true we thrown an exception. If we’ve allocated memory at the start of the function then the function needs to clean that up before the exception is thrown:

    Or just use smart pointers like std::unique_ptr that will do this for me.

  • Charlie

    You should add that most 64bit systems now have the "zero-cost exceptions". Basically, as I have understood, they store a table at a cold-code spot, so when no exception is thrown, it is as fast as no exception checking. Although when the program throws one, it is quite slower than normal 32bit exceptions. It also makes your executable file quite bigger!

  • Matt

    In your last code example, pJohn was not declared. Did you mean to declare pJohn inside of the try block?

  • Matt

    In your second from last sentence, "an" should be removed:
    "…which is a relatively an expensive operation."

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter