throw new exception- C#

Posted by Jalpesh P. Vadgama on ASP.net Weblogs See other posts from ASP.net Weblogs or by Jalpesh P. Vadgama
Published on Mon, 21 Oct 2013 18:31:01 GMT Indexed on 2013/10/21 21:54 UTC
Read the original article Hit count: 399

Filed under:

This post will be in response to my older post throw vs. throw(ex) best practice and difference- c# comment that I should include throw new exception.

What’s wrong with throw new exception:

Throw new exception is even worse, It will create a new exception and will erase all the earlier exception data. So it will erase stack trace also.Please go through following code. It’s same earlier post the only difference is throw new exception.

 

using System;

namespace Oops
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                DevideByZero(10);
            }
            catch (Exception exception)
            {
                throw new Exception
                (string.Format(
                    "Brand new Exception-Old Message:{0}",
                     exception.Message));
            }
        }

        public  static void DevideByZero(int i)
        {
           int j = 0;
           int k = i/j;
           Console.WriteLine(k);
          
        }
    }
}

Now once you run this example. You will get following output as expected.

Throw new exception C#

Hope you like it. Stay tuned for more..

Shout it

© ASP.net Weblogs or respective owner

Related posts about c#