Monday, October 21, 2013

throw new exception- C#

This post will be in response to my older post about throw exception best practice. where one of user asked that I should include throw new exception.So I thought it will be good idea to write a whole blog post for it. This blog post explains what's wrong with 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..
Share:

0 comments:

Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews