none
Why use "throw;" in a try catch?

    Question

  • I noticed that the Stock Trader sample application uses the following try..catch pattern:

    try
    {
         // Code...
    }
    catch
    {
         throw;
    }

    The question is, if "throw;" just re-throws the exception, why even bother using the try-catch? I mean, the calling method will get the same exception whether we use the above pattern or not.
    Friday, February 26, 2010 4:35 PM

Answers

  • In the example you posted, this is useless.  However, this is a useful practice:


    try
    {
       // Code
    }
    catch (Exception e) // catch any exception
    {
        LogException(e); // Log this...
        throw; // Rethrow
    }



    Reed Copsey, Jr. - http://reedcopsey.com
    • Marked as answer by Atarax Friday, February 26, 2010 4:53 PM
    Friday, February 26, 2010 4:47 PM

All replies

  • The only reason I can think of for this is that it gives you a place to stick a breakpoint.

    I surely wouldn't let this go into production, myself.

           -Steve
    Programming blog: http://nitoprograms.blogspot.com/
      Including my TCP/IP .NET Sockets FAQ
      and How to Implement IDisposable and Finalizers: 3 Easy Rules
    Microsoft Certified Professional Developer

    How to get to Heaven according to the Bible
    Friday, February 26, 2010 4:42 PM
  • In the example you posted, this is useless.  However, this is a useful practice:


    try
    {
       // Code
    }
    catch (Exception e) // catch any exception
    {
        LogException(e); // Log this...
        throw; // Rethrow
    }



    Reed Copsey, Jr. - http://reedcopsey.com
    • Marked as answer by Atarax Friday, February 26, 2010 4:53 PM
    Friday, February 26, 2010 4:47 PM
  • this 'throw' means, simply, that you don't want manage exceptions in this routine, but you want the exception re-trown to the caller, that, usually, is the object that has instanced this class.
    It may also be a 'todo not done' (programmer forget, or didn't care, because this is a learning sample)
    please, mark this as answer if it is THE answer
    ----------------
    Diego Cattaruzza
    Microsoft MVP - Visual Basic: Development
    blog: http://community.visual-basic.it/Diego
    web site: http://www.visual-basic.it
    Friday, February 26, 2010 4:48 PM