views:

135

answers:

2

I'm trying to decide between two ways of instantiating an object & handling any constructor exceptions for an object that is critical to my program, i.e. if construction fails the program can't continue.

I have a class SimpleMIDIOut that wraps basic Win32 MIDI functions. It will open a MIDI device in the constructor and close it in the destructor. It will throw an exception inherited from std::exception in the constructor if the MIDI device cannot be opened.

Which of the following ways of catching constructor exceptions for this object would be more in line with C++ best practices

Method 1 - Stack allocated object, only in scope inside try block

#include <iostream>
#include "simplemidiout.h"

int main()
{
    try
    {
        SimpleMIDIOut myOut;  //constructor will throw if MIDI device cannot be opened
        myOut.PlayNote(60,100);

        //.....
        //myOut goes out of scope outside this block
        //so basically the whole program has to be inside 
        //this block.
        //On the plus side, it's on the stack so 
        //destructor that handles object cleanup
        //is called automatically, more inline with RAII idiom?
    }
    catch(const std::exception& e)
    {
        std::cout << e.what() << std::endl;
        std::cin.ignore();
        return 1;
    }

    std::cin.ignore();
    return 0;   
}

Method 2 - Pointer to object, heap allocated, nicer structured code?

#include <iostream>
#include "simplemidiout.h"

int main()
{
    SimpleMIDIOut *myOut;

    try
    {
        myOut = new SimpleMIDIOut();
    }
    catch(const std::exception& e)
    {
        std::cout << e.what() << std::endl;
        delete myOut;
        return 1;
    }

    myOut->PlayNote(60,100);

    std::cin.ignore();

    delete myOut;
    return 0;

}

I like the look of the code in Method 2 better, don't have to jam my whole program into a try block, but Method 1 creates the object on the stack so C++ manages the object's life time, which is more in tune with RAII philosophy isn't it?

I'm still a novice at this so any feedback on the above is much appreciated. If there's an even better way to check for/handle constructor failure in a siatuation like this please let me know.

+2  A: 

Personally, I prefer the first style you've used - Method 1 - that of allocating the SimpleMIDIOut object as local to the scope of the try-catch block.

  • For me, one of the benefits of a try-catch block is that is provides a neat, tidy place for that error handling code - the catch block - that allows you to specify your business logic in one nice, readable, unbroken flow.

  • Secondly, the try-catch block you've specified is generic enough to deal with any exception that derives from std::exception - so having the bulk of your program code within the try-catch block isn't a bad thing. It'll prevent your program from terminating unexpectedly if the worst happens and an exception gets thrown. Potentially that could be an exception that you don't expect, like an index out of bounds, or a memory allocation exception.

  • If you dislike having lots of code within the try-catch block for readability reasons, that's OK, because it's good design practice to refactor big lumps of code into functions. By doing this, you can keep the main function itself to a minimal number of lines.

Looking at Method 2:

  • You don't need that delete in the catch block. If an exception was thrown during construction then there's no object there to delete anyway.

  • Have you considered how you plan to cater for any std::exception that could be thrown by myOut->PlayNote? It's outside the scope of your try-catch, so an exception here would kill the program unexpectedly. This is what I was getting at with my second bullet, above.

If you were to decide to wrap most of the program in that try-catch block, but would still like to dynamically allocate the SimpleMIDIOut object, you could make the memory management a bit easier by using an auto_ptr to manage the memory for you in the event of an exception:

try
{
    std::auto_ptr<SimpleMIDIOut> myOut(new SimpleMIDIOut());
    myOut->PlayNote(60,100);
    std::cin.ignore();
} // myOut goes out of scope, SimpleMIDIOut object deleted
catch(const std::exception& e)
{
    std::cout << e.what() << std::endl;
    return 1;
}


return 0;

...but you may as well just create the SimpleMIDIOut object as local rather than dynamic.

sgreeve
Thanks for the detailed reply. Food for thought. Wedging it all into that try/catch block seems weird to me on an aesthetic level and I wanted to a bit of a sanity check on that code structure.
MTLPhil
It may sounds weird, but it's in fact a very good practice to enclose the code in `main` into a try/catch block to prevent an unexpected termination (and log the exception for analysis). I should note though that it's kind of a desperate measure and only applicable to `main` and main-like functions, don't take the habit to enclose every function body into a try/catch ;)
Matthieu M.
+1  A: 

Can you clarify if you have control over the source code in SimpleMIDIOut?

If you do the this class should not throw an exception from the CTOR. The code in the CTOR of that class should be wrapped with a try\catch block.

If you don't then I would go with method 1 for clarity - the fact that the whole program will have to be in this try block can be solved be refactoring into small methods.

David Relihan
It's perfectly valid to throw an exception from a constructor, to indicate to the caller that for whatever reason construction could not be completed.
sgreeve
Its valid - but in my opinion it is bad design that could lead to run time exceptions
David Relihan
@drelihan The alternative is to allow construction of an object in an unusable state, and then wait for it to be used somewhere. A much poorer design choice IMHO.
sgreeve
@sgreeve Fair point - but C++ destroys only fully constructed objects, and an object isn't fully constructed until its constructor has completed. This could lead to undefined behaviour - particualrly if new memory had been allocated etc...
David Relihan
@drelihan Also a very fair point. An argument for a well-written constructor that mops up the memory it allocated if it fails.
sgreeve
All the constructor of the class does is make a call to Win32 API function midiOutOpen() to get a MIDI device handle and then checks the return value for success/failure. Throws exception on fail of the open operation. Nothing is dynamically allocated in the constructor. In a circumstance like this, is there anything that needs mopping up if the constructor fails?
MTLPhil
@mtlphil No, not on this occasion.
sgreeve