I can't understand how to handle an exception in a method which returns value, in my case the value of Person[] type. I tried to do as written here - Creating and Throwing Exceptions, but I'm still getting an exception in - throw icex; line. Could someone please give me a hint? I also tried to return null in catch block, instead of throw, but I only get another exception.(I'm using ArrayList instead of List intentionally)
static ArrayList CreateNonGenericList()
{
ArrayList personList = new ArrayList()
{
new Person {FirstName="John", LastName="Clark", Age=39,
StartDate= new DateTime(1989, 12, 30)},
new Person{FirstName="Zefa", LastName="Thoms", Age=23,
StartDate= new DateTime(2003, 4, 12)},
new Person{FirstName="Robin", LastName="Hood", Age=33,
StartDate= new DateTime(2001, 4, 12)}
};
personList.Add("John"); //Passing a String value instead of Person
return personList;
}
static Person[] SortNonGenericList(ArrayList personList)
{
try
{
Person[] latestpersonList = (from Person p in personList
where p.StartDate > new DateTime(2000, 1, 1)
select p).ToArray();
return latestpersonList;
}
catch (InvalidCastException ex)
{
InvalidCastException icex = new InvalidCastException(ex.Message, ex);
throw icex; //Getting an InvalidCastException here
}
}