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.