difference between throw exception in rethrow - طراحی سایت|نرم افزار اندروید|IOS|مرورگران

difference between throw exception in rethrow

In some cases needs to throw an exception to notify the caller something bad was being happened but to logging the exact line code in which the exception happened reThrowing should be used.

Let’s dive into code and look at it practically.

using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var radio = new Radio();
            radio.SetVolume(120);
        }

        class Radio
        {
            public int Volume { get; set; }
            public string Station { get; set; }

            public void SetVolume(int? volume)
            {
                if (volume > 100)
                {
                    throw new ArgumentOutOfRangeException(nameof(volume), "volume cannot be more than 100");
                }

                Volume = volume;
                 try
                 {
                     SetStation(volume?.ToString());
                 }
                 catch(exception ex)
                 {
                     DoLog();
                     throw ex;
                 }
            }

            public void SetStation(string station)
            {
                if (string.IsNullOrEmpty(station))
                {
                    throw new ArgumentNullException(nameof(station), "you cannot tune to an empty station");
                }

                Station = station;
            }
        }
    }
}

At Above code if volume be null, SetStation() thow exception and program will go through catch statement, in catch some procedure will execute and then again throw another exception.

This new throw cause stacktrace was being overrighted and this throw line number will be displayed at output.

To resolve this, Rethrow ability of C# will give us hand and prevent the stack trace is being overrighted so e should refactor catch body with

catch(exception ex)
{
DoLog();
throw; //rethrow
}

we will have proper information of where the exception has accured truelly.

    نظر خود را بگذارید

    آدرس ایمیل شما منتشر نخواهد شد.*