Swallowing exception thrown in catch/finally block
<p>Usually I come across situations where I have to swallow an exception thrown by the clean up code in the <code>catch</code>/<code>finally</code> block to prevent the original exception being swallowed.</p>

<p>For example:</p>

<pre><code>// Closing a file in Java
public void example1() throws IOException {
    boolean exceptionThrown = false;
    FileWriter out = new FileWriter(“test.txt”);
    try {
        out.write(“example”);
    } catch (IOException ex) {
        exceptionThrown = true;
        throw ex;
    } finally {
        try {
            out.close();
        } catch (IOException ex) {
            if (!exceptionThrown) throw ex;
            // Else, swallow the exception thrown by the close() method
            // to prevent the original being swallowed.
        }
    }
}

// Rolling back a transaction in .Net
public void example2() {
    using (SqlConnection connection = new SqlConnection(this.connectionString)) {
        SqlCommand command = connection.CreateCommand();
        SqlTransaction transaction = command.BeginTransaction();
        try {
            // Execute some database statements.
            transaction.Commit();
        } catch {
            try {
                transaction.Rollback();
            } catch {
                // Swallow the exception thrown by the Rollback() method
                // to prevent the original being swallowed.
            }
            throw;
        }
    }
}
</code></pre>

<p>Let's assumed that logging any of the exceptions is not an option in the scope of method block, but will be done by the code calling the <code>example1()</code> and <code>example2()</code> methods.</p>

<p>Is swallowing the exceptions thrown by <code>close()</code> and <code>Rollback()</code> methods a good idea? If not, what is a better way of handling the above situations so that the exceptions are not swallowed?</p>
