try{
return A[key1].Keys.Union(B[key1].Keys).ToList();
}
catch(KeyNotFoundException ex)
{}
任务是找到A [key1]和B [key1]以及" unite"的所有键。他们。 但是A [key1]和B [key1]可以抛出异常,我想知道我怎么知道A对象或B对象是否抛出了这些异常?
答案 0 :(得分:2)
使用您发布的代码块,这是不可能的。但是,您可以尝试获取它们的值或检查它们是否存在:
if(!A.ContainsKey(key1)) // A didn't have key1
return null; // Maybe throw exception?
if(!B.ContainsKey(key1)) // B didn't have key1
return null; // Maybe throw a different exception?
return A[key1].Keys.Union(B[key1].Keys).ToList();
或稍快一些(因为它们已经被搜索过了)
type a, b; // Type must be the type that A[key1] and B[key1] contains
if(!A.TryGetValue(key1, out a)) // A didn't have key1
return null; // Maybe throw exception?
if(!B.TryGetValue(key1, out b)) // B didn't have key1
return null; // Maybe throw a different exception?
return a.Keys.Union(b.Keys).ToList();