我无法理解如何在返回值的方法中处理异常,在我的情况下,该值是Person []类型的值。我试图按照这里写的那样-创建和抛出异常,但是我仍然遇到异常-抛出icex; 线。有人可以给我一个提示吗?我也尝试在catch块中返回null而不是throw,但是我只得到另一个异常(我故意使用ArrayList而不是List)
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
}
}
如果您只想让方法的调用者处理该异常,则可以try/catch
完全删除该块。未捕获到异常时,它们会自动“冒泡”。
如果要在catch
块中执行某些操作(例如记录),则应引发原始异常:
catch (InvalidCastException ex)
{
// Log(ex);
throw;
}
这样,异常中的堆栈跟踪不会像当前代码中那样“重置”。
正如其他人指出的那样,您当前正在做的事情是没有用的,因为您正在抛出具有相同类型和消息的新异常。尽管例如,如果您想要一个更具描述性的异常,则创建一个新异常可能会很有用:
catch (InvalidCastException ex)
{
throw new ApplicationException("Unable to Sort list because at least one person has no StartDate", ex);
}
然后,该异常仍将在catch块中“发生”,但是其描述将为代码中的该位置提供有用的信息。
当然,最后您必须实际处理该异常。如果无法对personList排序,该怎么办?以原始顺序归还它们吗?退出应用程序?告诉最终用户操作失败?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句