Rethrowing Exceptions - Best Practice?

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

Kent Boogaart

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?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top