StefanL19 StefanL19 - 2 months ago 10
C# Question

Return information with Custom Exceptions C#

I have the following problem:


  1. I have a service method:

    public bool EmployeeCanReiceivePayment(int employeeId)
    {
    ...

    int workingHours = this.GetEmployeeWorkingHours(employeeId);

    if(workingHours < N)
    {
    throw new EmployeeCannotReceivePaymentException();
    }

    return true;
    }

    public int GetEmployeeWorkingHours(int employeeId)
    {
    //returns the number of working hours of the employee for the last month
    }



GetEmployeeWorkingHours is just one of the methods to check if the employee can receive salary (so there can be another reason for the employer not to pay). For each of this reasons I want to throw an exception with the appropriate information: Number of required working hours, number of the actual working hours etc..

The question is:

Is there a way to return an object or additional information with my Custom exception. And by additional information I mean an object or just several paramenters.

Answer

Here is full example in dot net fiddle !

You need to create custom exception and inherit from Exception, after that you can create constructor with your object using one of the base constructors.

    public class CustomObject
    {
        public string Name { get; set; }
    }


    public class CustomException : Exception
    {
        private CustomObject _customObjectProp;

        public CustomObject CustomObjectProp
        {
            get { return _customObjectProp; }
            set { _customObjectProp = value; }
        }
        public CustomException(string message, CustomObject obj):base(message)
        {
            _customObjectProp = obj;
        }
    }

    static void Main(string[] args)
    {
        int a = 5;
        int b = 6;

        try
        {
            if (b > a)
            {
                CustomObject obj = new CustomObject();
                obj.Name = "test";

                throw new CustomException("Test Message", obj);
            }

        }
        catch(CustomException ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine(ex.CustomObjectProp.Name);
        }
    }
Comments