Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In .NET, is there any advantage to a try/catch where the catch just rethrows [duplicate]

Tags:

c#

.net

try-catch

Possible Duplicate:
Why catch and rethrow Exception in C#?

I sometimes come across C# code that looks like this:

        try
        {
            // Some stuff
        }
        catch (Exception e)
        {
            throw e;
        }

I understand its possible to do something like log the exception message and then rethrow it. I'm talking about a catch that only rethrows the exception. I don't see a point to this. I have three questions:

1) Is there any advantage to this

2) Does this slow doen the code at all

3) Would it make any difference if the catch block were as follows:

        catch (Exception)
        {
            throw;
        }
like image 978
Justin Dearing Avatar asked Jul 30 '09 14:07

Justin Dearing


2 Answers

This rethrows the exact same exception:

    catch (Exception)
    {
        throw;
    }

Whereas this rethrows the exception without the original stack trace:

    catch (Exception e)
    {
        throw e;
    }

There is often a good reason for throw; as you can log the exception or do other things prior to rethrowing the exception. I am not aware of any good reasons for throw e; as you will wipe out the valuable stack trace information.

like image 185
Andrew Hare Avatar answered Nov 15 '22 06:11

Andrew Hare


Not if you do nothing else in the catch... But this is often used to do other things in the catch, such as logging, or other kinds of exception procesing, before rethrowing it.

like image 20
Charles Bretana Avatar answered Nov 15 '22 07:11

Charles Bretana