Swallowing exception thrown in catch/finally block
c#, java
Solution
I'm not a fan of catching and rethrowing an exception.
If you catch it, do something with it - even if it's just logging the exception.
If you can't do anything with it, don't catch it - add a throws clause to the method signature.
Catching an exception tells me that either you can deal with an exceptional situation and have a recovery plan or "the buck stops here" because an exception cannot propagate in that form any farther (e.g., no stack traces back to the user).
Problem
Usually I come across situations where I have to swallow an exception thrown by the clean up code in the `catch`/`finally` block to prevent the original exception being swallowed. For example: ``` // 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; } } } ``` 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 `example1()` and `example2()` methods. Is swallowing the exceptions thrown by `close()` and `Rollback()` methods a good idea? If not, what is a better way of handling the above situations so that the exceptions are not swallowed?