Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Personally, I prefer the first style you've used</strong> - Method 1 - that of allocating the <code>SimpleMIDIOut</code> object as local to the scope of the try-catch block. </p> <ul> <li><p>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. </p></li> <li><p>Secondly, the try-catch block you've specified is generic enough to deal with any exception that derives from <code>std::exception</code> - 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. </p></li> <li><p>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 <a href="http://www.refactoring.com/catalog/extractMethod.html" rel="nofollow noreferrer">refactor big lumps of code into functions</a>. By doing this, you can keep the main function itself to a minimal number of lines. </p></li> </ul> <p><strong>Looking at Method 2:</strong> </p> <ul> <li><p>You don't need that <code>delete</code> in the catch block. If an exception was thrown during construction then there's no object there to delete anyway. </p></li> <li><p>Have you considered how you plan to cater for any <code>std::exception</code> that could be thrown by <code>myOut-&gt;PlayNote</code>? 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. </p></li> </ul> <p>If you were to decide to wrap most of the program in that try-catch block, but would still like to dynamically allocate the <code>SimpleMIDIOut</code> object, you could make the memory management a bit easier by using an <a href="http://en.wikipedia.org/wiki/Auto_ptr" rel="nofollow noreferrer">auto_ptr</a> to manage the memory for you in the event of an exception: </p> <pre><code>try { std::auto_ptr&lt;SimpleMIDIOut&gt; myOut(new SimpleMIDIOut()); myOut-&gt;PlayNote(60,100); std::cin.ignore(); } // myOut goes out of scope, SimpleMIDIOut object deleted catch(const std::exception&amp; e) { std::cout &lt;&lt; e.what() &lt;&lt; std::endl; return 1; } return 0; </code></pre> <p>...but you may as well just create the <code>SimpleMIDIOut</code> object as local rather than dynamic. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload