Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Re-throw Exceptions?

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?)

like image 925
tghoang Avatar asked Sep 22 '08 07:09

tghoang


People also ask

What is the purpose of re-throwing an exception?

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.

Why is throwing an exception better than returning an error value?

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.

What is re-throwing an exception means in C++?

a) An exception that is thrown again as it is not handled by that catching block.


2 Answers

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.

like image 107
Chris Jester-Young Avatar answered Sep 22 '22 21:09

Chris Jester-Young


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);     }  } 
like image 31
Davy Landman Avatar answered Sep 20 '22 21:09

Davy Landman