Rethrowing Exceptions - Best Practice?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Martin Smith

    Rethrowing Exceptions - Best Practice?

    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?
  • Kent Boogaart

    #2
    Re: Rethrowing Exceptions - Best Practice?

    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(s tring itemName) {
    try {
    //try and read file here
    } catch (IOException e) {
    throw new ConfigurationEx ception(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 (ConfigurationE xception). 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 ConfigurationEx ception instead.

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

    HTH,
    Kent

    "Martin Smith" <anonymous@disc ussions.microso ft.com> wrote in message
    news:9EFD49FC-C230-4214-88B4-67BFC60AAE57@mi crosoft.com...[color=blue]
    > If a class has no need for any specific clean up code in a particular[/color]
    catch block is there any benefit to catching and rethrowing exceptions,
    rather than just letting the original exception bubble up to the calling
    function?[color=blue]
    >
    > If so what?[/color]


    Comment

    • Martin

      #3
      Re: Rethrowing Exceptions - Best Practice?

      Hi Kent

      Thanks for your most comprehensive answer

      - Martin

      Comment

      Working...