Home > Back-end >  C# throw exception or ToString to ref string parameter
C# throw exception or ToString to ref string parameter

Time:10-10

In case I write a dll for consumers, What is better in catch scope, throw an exception or write it to reference or out string parameter?

As far as I know exceptions ensure that failures do not go unnoticed because calling code didn't check a return code. https://docs.microsoft.com/en-us/dotnet/standard/exceptions/best-practices-for-exceptions

Which is the best between the following 2 options?

OptionA

static void ThrowException(string value)
{
    try
    {
        //Some code....
    }
    catch (Exception)
    {
        //Log Exception
        throw;
    }
}

Option B

static void RefException(string value, ref string errorMessage)
{
    try
    {
        //Some code...
    }
    catch (Exception ex)
    {
        //Log Exception
        errorMessage = ex.ToString();
    }
}

CodePudding user response:

Option A when you are validating some specific condition it will notify client with proper error message. Though other option are also doing same thing by throwing exception but it is not good practice to throw an exception for Validation. If any exception occur in application it is not good practice to throw exception with all details because it can lead to security threat by giving unnecessary details to client application. It is always recommended to log it in and show modified message to client application.

In this case you should go with throw Exception because you can pass custom message to client application and when you go with ref option there might be possibility that error message might get modified by another component of application which could mislead information of exception.

CodePudding user response:

I believe you are looking to create custom exceptions other than the .net exception

Update your code with the below code and create custom exceptions according to your need.

    public void ThrowException()
    {
       
               if (string.IsNullOrEmpty(value))
                {
                    throw new NullException();
                }
                
                 if (value.Length > 10)
                {
                    throw new LengthException();
                }
        
     }
     
    
    
    public class NullException : Exception
    {
        NullException() : base(NullException.GetMessage())
        {
        }
        
         public static string GetMessage()
        {
            return "value is null or empty";

        }
    }
    
    public class LengthException : Exception
    {
        LengthException() : base(LengthException.GetMessage())
        {
        }
        
         public static string GetMessage()
        {
            return "value length greater then 10 exception";

        }
    }
  • Related