Good style for handling constructor failure from a critical object

I am trying to decide between two ways to instantiate an object and handle any constructor exceptions for an object that is critical to my program, that is, if the construction is not completed, the program cannot continue.

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

Which of the following methods to catch constructor exceptions for this object will be more consistent with C ++ best practices.

Method 1 - the selected object, only in the area inside the 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 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;   
}

2 - , , ?

#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;

}

2 , try, 1 , ++ , RAII, ?

, . / , , .

+5
2

, . 1 - SimpleMIDIOut try-catch.

  • try-catch , , - catch - - , , .

  • -, try-catch , std::exception - try-catch . , , . , , , .

  • try-catch , , . , .

2:

  • , delete catch. , .

  • , std::exception, myOut->PlayNote? try-catch, . , , .

try-catch, SimpleMIDIOut, , auto_ptr :

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;

... SimpleMIDIOut , .

+2

, SimpleMIDIOut?

, CTOR. CTOR try\catch.

, 1 - , try, .

+1

All Articles