locked
quick question on catching exceptions RRS feed

  • Question

  • hello,

    what is the recommended ('best practice') way to structure your code to catch multiple types of exceptions?

    1) do you use muliple 'catch' blocks, each with a specific exception type? or is there a way to just catch system.exception in one catch block but then test that system.exception for it's more specific type?

    2) I'm assuming the more specific exception types include more detailed information? or is their advantage *only* that you know that much more about what happened because you caught *that* type?
    Thursday, October 29, 2009 4:05 PM

Answers

All replies

  • 1. Multiple catch blocks ordered from most specific to least specific.... ie, "Exception" should be the last one.

    2. Typically, this is the case.  But the main advantage is that you know more about what happened based on the exception type.
    Coding Light - Illuminated Ideas and Algorithms in Software
    Coding Light WikiLinkedInForumsBrowser
    Thursday, October 29, 2009 4:07 PM
    Moderator
  • Better is to use multiple catch block for handling exceptions. But the important thing is that we can avoid exceptions.

    For example. checking whether object is null or not by if statement

    if (obj ! = null)
    {
      // do some thing
    }

    rather then

    try
    {
       // use obj
    }
    catch(Exception ex) {}

    similarly, checking whether connection is opened or closed  by checking its status

    Following links provide best practices of exception handling

    http://msdn.microsoft.com/en-us/library/seyhszts.aspx

    http://www.codeproject.com/KB/architecture/exceptionbestpractices.aspx
    Thursday, October 29, 2009 4:15 PM
  • thank you both for the info, its appreciated.
    Thursday, October 29, 2009 5:54 PM
  • Hi,

    Multiple catch statement is the best one.
    Because the main use of the Try catch is to show some valid message to end user.
    End user dont know abt the exception. Some null exception while saving the details then we need to display in the UI like "Error while saving details". So if you are going to use try catch use multiple catch and throw valid message.

    Note:

    In performance point of view try to avoid try catch block. 

    How it affects performance:

    Exceptions are probably one of the heaviest resource hogs and causes of slowdowns you will ever see in web applications, as well as windows applications.

    Solution:

    You can use as many try/catch blocks as you want. Using exceptions gratuitously is where you lose performance. For example, you should stay away from things like using exceptions for control flow.
    • Proposed as answer by Bala.Nattarasan Thursday, December 10, 2009 4:36 AM
    Monday, November 2, 2009 6:21 AM