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;
myOut.PlayNote(60,100);
}
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, ?
, . / , , .