locked
C# Throwing Exceptions while returning a type RRS feed

  • Question

  • Hi,

    I would like to seek expert opinion on throwing custom exceptions while returning a type. Got two ways to do as in the following code snippets (1 and 2).

    What is the best possible way? Please help if there are any other way?


    Code Snippet 1:
    private string GenerateClientIdInBase64(string clientID)
    {
        try
        {
            byte[] bytes = Encoding.UTF8.GetBytes(clientID);
            string base64ClientID = Convert.ToBase64String(bytes);
            return base64ClientID;
        }
        catch (ArgumentOutOfRangeException ex)
        {
            throw new PayPalException(ex.Message, ex);
        }
        catch (ArgumentException ex)
        {
            throw new PayPalException(ex.Message, ex);
        }
        catch (NotSupportedException ex)
        {
            throw new PayPalException(ex.Message, ex);
        }
        catch (System.Exception ex)
        {
            throw new MyCustomException(ex.Message, ex);
        }
    }

    Code Snippet 2:
    private string GenerateClientIdInBase64(string clientID)
    {
        string base64ClientID = null;
        try
        {
            byte[] bytes = Encoding.UTF8.GetBytes(clientID);
            base64ClientID = Convert.ToBase64String(bytes);
        }
        catch (ArgumentOutOfRangeException ex)
        {
            throw new PayPalException(ex.Message, ex);
        }
        catch (ArgumentException ex)
        {
            throw new PayPalException(ex.Message, ex);
        }
        catch (NotSupportedException ex)
        {
            throw new PayPalException(ex.Message, ex);
        }
        catch (System.Exception ex)
        {
            throw new MyCustomException(ex.Message, ex);
        }
        return base64ClientID;
    }

    Code Snippet 3:
    public class MyCustomException : System.Exception
    {
        private static readonly ILog logger = LogManagerWrapper.GetLogger(typeof(MyCustomException));

        public MyCustomException() : base() { }   
       
        public MyCustomException(string message): base(message)
        {
     if (logger.IsErrorEnabled)
       {
        logger.Error(message, this);
       }
        }


        public MyCustomException(string message, System.Exception cause) : base(message, cause)
        {
       if (logger.IsErrorEnabled)
       {
            logger.Error(message, this);
       }
        }
    }

    Thanks


    • Edited by recherche Wednesday, January 30, 2013 5:28 AM typo
    Wednesday, January 30, 2013 5:25 AM

Answers

  • That is the thing. When you throw an exception it IS the return value.

    That is the reason the compiler won't complain if you implement an interface and all the functions that return values contain is

    throw new NotImplementedExcpetion();

    It will return a value in 100% of the code paths.

    What you want to archive is basically "more then one return value". At least two ways to do that:

    Write a Structure or Custom Class with multiple fields. Return that structure or custom class. For example all EventHandlers have the similar parameters: object Sender, and a variable "e" whose type is either EventArgs or a custom type derived from EventArgs (like MouseEventArgs).

    Out & Ref. Those two keywords are similar to using a pointer in another language. They give variable into the Fucntion (Call by Reference) instead of making a copy of the Variable (Call by Value). Thus changes made inside the function affect the variable outside the function.

    • Marked as answer by Jason Dot Wang Thursday, February 7, 2013 2:36 AM
    Wednesday, January 30, 2013 8:42 AM
  • In both the snippets you are rethrowing a custom exception and control never reaches the return statements. you can return the value if you do not rethrow the exception or you can create a property in MyCustomException for the purpose of returning the value.
    • Proposed as answer by Konrad Neitzel Wednesday, January 30, 2013 5:55 AM
    • Marked as answer by Jason Dot Wang Thursday, February 7, 2013 2:36 AM
    Wednesday, January 30, 2013 5:38 AM

All replies

  • In both the snippets you are rethrowing a custom exception and control never reaches the return statements. you can return the value if you do not rethrow the exception or you can create a property in MyCustomException for the purpose of returning the value.
    • Proposed as answer by Konrad Neitzel Wednesday, January 30, 2013 5:55 AM
    • Marked as answer by Jason Dot Wang Thursday, February 7, 2013 2:36 AM
    Wednesday, January 30, 2013 5:38 AM
  • I would go for the first one because it is more readable than second one. I mean, someone doesn't need to go all the way down to see what is the return  value.

    Other than readability, there isn't any difference between those two.

    I hope this helps.


    Please mark this post as answer if it solved your problem. Happy Programming!

    Wednesday, January 30, 2013 5:39 AM
  • That is the thing. When you throw an exception it IS the return value.

    That is the reason the compiler won't complain if you implement an interface and all the functions that return values contain is

    throw new NotImplementedExcpetion();

    It will return a value in 100% of the code paths.

    What you want to archive is basically "more then one return value". At least two ways to do that:

    Write a Structure or Custom Class with multiple fields. Return that structure or custom class. For example all EventHandlers have the similar parameters: object Sender, and a variable "e" whose type is either EventArgs or a custom type derived from EventArgs (like MouseEventArgs).

    Out & Ref. Those two keywords are similar to using a pointer in another language. They give variable into the Fucntion (Call by Reference) instead of making a copy of the Variable (Call by Value). Thus changes made inside the function affect the variable outside the function.

    • Marked as answer by Jason Dot Wang Thursday, February 7, 2013 2:36 AM
    Wednesday, January 30, 2013 8:42 AM
  • A good example is TryParse(). Tryparse aims to make transfomring a string into a Numeric value easier.

    Normal the Parse function will, if it encoutners any problems, throw an exception. Wich would then have to be caught with a catch block and handeled rathercomplily.

    TryParse() does not throw an error if the parsing fails. It also doesn't give you the parsed number via Return Value. Instead it's return value is boolean!

    If will return true if the conversion was successfull. It will return false if it was unsuccesfull. However it has two parameters: the string to be parsed, and a out parameter of the type you wish.

    You use it like this:

    string input; int parsedValue; if(Int32.TryParse(input, out parsedValue)){ //The value was parsed succesfully. parsedValue contains the parsed value,
    //wichever it may be } else{ //The value was not parsed sucessfully. parsedValue is 0.
    //You can here do your stuff to handle the invalid input }

    Wednesday, January 30, 2013 8:55 AM