在我的代码中,有很多区域我们手动"throw" InvalidOperationException异常。我们有特定的处理程序来处理这种异常类型。但是有一个要求,我们必须根据异常是否是由throw引起的还是来自系统而编写一些逻辑。以下是示例:
static void Main(string[] args)
{
try
{
Console.WriteLine("Hello World!");
//throwFirstLayer(); //if i uncomment this i am throwing the error manually
var people = new List<Person>();
people.Add(new Person("John", "Doe"));
people.Add(new Person("Jane", "Doe"));
people.Sort(); //Suppose in this line system throws InvalidOp exception
foreach (var person in people)
Console.WriteLine("{0} {1}", person.FirstName, person.LastName);
}
catch(InvalidOperationException ioex)
{
var e = ioex;
}
}
public static void throwFirstLayer()
{
throw new InvalidOperationException("manual");
}
public class Person
{
public Person(String fName, String lName)
{
FirstName = fName;
LastName = lName;
}
public String FirstName { get; set; }
public String LastName { get; set; }
}
我希望在catch块内检测异常是由我手动从代码中抛出还是系统由于实际的无效操作引发的?