Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>At least two approaches come to mind, which are usually going to be <strong>combined</strong> depending on what you want <code>foo</code> to do:</p> <h3>1. Catch and rethrow only the relevant exceptions</h3> <p>There are only so many exceptions the code in your main flow can throw (probably mostly <code>SqlException</code>s). So only catch and rethrow those, and declare that you're doing so. More to the point, rethrow only the ones you're not actually handling (in your simplified sample code, you're not handling any, but your real life code is probably more subtle).</p> <p>Mind you, some of the exceptions may be runtime exceptions, and so you may want to combine this with the below.</p> <h3>2. Don't catch the exception at all</h3> <p>Like this:</p> <pre><code>// Signature changes to include any exceptions that really can be thrown public void foo() throws XYZException, ABCException { // A flag indicating that the commit succeeded boolean done = false; begin(); try { // Don't have any `return` statements in here (or if you do, // set `done` to `true` first) ... commit(); done = true; // Commit didn't throw an exception, we're done } finally { // finally clause always happens regardless if (!done) { // We must be processing an exception; rollback try { rollback(); } catch (Exception e) { // quash it (e.g., leave this block empty), we don't want // to mask the real exception by throwing a different one } } } } </code></pre> <p>Naturally your signature needs to include any exceptions that may be thrown in the main flow, but that's what you're trying to do, if I'm understanding you correctly.</p> <p>Again, you may well <strong>combine</strong> these two approaches, because you may want to <em>handle</em> some exceptions and not others.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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