I've seen the following code many times:
try { ... // some code } catch (Exception ex) { ... // Do something throw new CustomException(ex); // or // throw; // or // throw ex; }
Can you please explain the purpose of re-throwing an exception? Is it following a pattern/best practice in exception handling? (I've read somewhere that it's called "Caller Inform" pattern?)
Re-throwing Exceptions When an exception is caught, we can perform some operations, like logging the error, and then re-throw the exception. Re-throwing an exception means calling the throw statement without an exception object, inside a catch block. It can only be used inside a catch block.
When you code using return codes, you're preparing yourself for failure, and hope your fortress of tests is secure enough. When you code using exception, you know that your code can fail, and usually put counterfire catch at chosen strategic position in your code.
a) An exception that is thrown again as it is not handled by that catching block.
Rethrowing the same exception is useful if you want to, say, log the exception, but not handle it.
Throwing a new exception that wraps the caught exception is good for abstraction. e.g., your library uses a third-party library that throws an exception that the clients of your library shouldn't know about. In that case, you wrap it into an exception type more native to your library, and throw that instead.
Actually there is a difference between
throw new CustomException(ex);
and
throw;
The second will preserve the stack information.
But sometimes you want to make the Exception more "friendly" to your application domain, instead of letting the DatabaseException reach your GUI, you'll raise your custom exception which contains the original exception.
For instance:
try { } catch (SqlException ex) { switch (ex.Number) { case 17: case 4060: case 18456: throw new InvalidDatabaseConnectionException("The database does not exists or cannot be reached using the supplied connection settings.", ex); case 547: throw new CouldNotDeleteException("There is a another object still using this object, therefore it cannot be deleted.", ex); default: throw new UnexpectedDatabaseErrorException("There was an unexpected error from the database.", ex); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With