Link to home
Start Free TrialLog in
Avatar of ipjyo
ipjyoFlag for United States of America

asked on

How to maintain the list of all the exceptions in a List<> object in C#?

Hi,

I need to maintain a list of all exceptions in a List<> object. In the attached code below, I have a method 'Import' which will invoke another method 'SetField' in a for loop and I need to be able to capture any exceptions and continue with invoking the 'SetField' for the rest of the items. In the calling program, I need to check if there are any errors as below. But I am not able to access the list 'ErrorMessages' on the 'errors' object in the calling program. I am missing something here. Can anybody please provide any suggestions? Thank you.

//Calling program
Fields f = new Fields();
f.Import();
if(errors.ErrorMessages.Count > 0)
{
//loop through each message here.
}
public class Exceptions
    {
        List<string> ErrorMessages = new List<string>();

        public void Add(string field, int instance, string error)
        {
            ErrorMessages.Add(string.Format("Error '{0}' occured while setting the field {1} and instance {2}", error, field, instance));
        }
    }


class Fields
{

public Exceptions errors { get; set; }

public void Import()
{
	
	foreach(var item in fields)
	{
		try
		{
			SetField(item.field, item.instance)
		}
		catch(Exception x)
		{
			errors.Add(item.field, item.instance, x.Message)	
		}
	}
}

}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ipjyo

ASKER

Thank you. Also, I am trying to add error messages using the property of type 'Exceptions' as below.

public Exceptions errors { get; set; }

errors.Add(item.field, item.instance, x.Message)      

Also, I will need to access this property to look for the errors in a different assembly as below. But I am not able to access the property 'Errors' of type <List>. The intellisense is showing only the property 'errors' but not the poperty defined in 'Exceptions'.

//Calling assembly
Fields f = new Fields();
f.Import();
if(errors.Errors.Count > 0)
{
//loop through each message here.
}

class Fields
{

public Exceptions errors { get; set; }

public void Import()
{
	
	foreach(var item in fields)
	{
		try
		{
			SetField(item.field, item.instance)
		}
		catch(Exception x)
		{
			errors.Add(item.field, item.instance, x.Message)	
		}
	}
}

}

Open in new window

Avatar of ipjyo

ASKER

I am sorry. my bad. I am able to access the property 'Errors' from a different assembly. Please ignore my previous comment.

Thanks for your help.
NP. Glad to help  = )