1

I have code with try and catch.

try
{
    // Some code...
}
catch (Exception err)
{
     throw err;
}

Is there an advantage in writing such code?

To throw the exception from the catch and to write try and catch instead of getting an error from the line that break.

1
  • 6
    If written as is, there is no benefit, only downside of screwing up the StackTrace Commented May 16, 2017 at 14:09

3 Answers 3

6

You should only catch an exception if you intend to do something with it. For example, to add extra information to it, log it to a file or something like that, or change the exception:

try
{
    //Some Code...
}
catch (WebException err)
{
    throw new LicenseException("This was really bad!", err);
}
catch (Exception err)
{
    err.Data.Add("some-info", 123);

    logFramework.Log(err);

    throw;
}

Never ever rethrow the same exception (throw err): you lose the call stack when you do that. Instead, just throw, which retains the call stack.

Sign up to request clarification or add additional context in comments.

4 Comments

can you please add a finally{} in here and I'll upvote
Finally for what? What purpose would it serve in this sample? @MadMyche Is that part of the question?
No, but if we as a collective are trying to fix and use best practices, I would throw in some cleanup code
What is there to clean up? I can add a 100 best practices in this sample code, but it would all be irrelevant to the question asked.
0

In both options you have to catch the exception on a higher level. The first option (your code) gives you an opportunity to react to an exception or make additional logs.

Comments

0

Sometimes such an approach can be used, but generally it's not recommended.

Also, if you need to throw an exception like this, you need to change your code a little bit:

    try
     {
        //Some Code...
     }
    catch (Exception err)
     {
         //I'll recommend to remove err here, because if not you'll lose  the full stack trace.
         throw;
     }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.