Rethrowing Exceptions - Best Practice?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

If a class has no need for any specific clean up code in a particular catch block is there any benefit to catching and rethrowing exceptions, rather than just letting the original exception bubble up to the calling function

If so what?
 
If you were to do nothing but rethrow the same exception, there is no
benefit. If you were to catch the exception and throw a *different*
exception that better explains the context of the error, that would be
useful.

Suppose you have a helper class that obtains some configuration information
from a file:

public object GetConfigItem(string itemName) {
try {
//try and read file here
} catch (IOException e) {
throw new ConfigurationException(string.Format("Could not get
configuration item called '{0}'", itemName), e);
}
}

Now, instead of the client code receiving an IOException, they receive a
more specific exception (ConfigurationException). The client code should not
be concerned with how the configuration items are stored. For example, in
the future, you might want to change your app so that this configuration is
stored in a database. That's fine, you would just catch database-specific
exceptions and throw a ConfigurationException instead.

Notice how the ConfigurationException contains the original exception
(IOException) in it.

HTH,
Kent

Martin Smith said:
If a class has no need for any specific clean up code in a particular
catch block is there any benefit to catching and rethrowing exceptions,
rather than just letting the original exception bubble up to the calling
function?
 
Back
Top