如何知道是什么对象抛出了异常?
How to know what object threw an exception?
try{
return A[key1].Keys.Union(B[key1].Keys).ToList();
}
catch(KeyNotFoundException ex)
{}
任务是从 A[key1] 和 B[key1] 中找到所有的键并 "unite" 它们。
但是 A[key1] 和 B[key1] 可以抛出异常,我想知道我怎么知道是 A 对象还是 B 对象抛出了这些异常?
使用您发布的代码块,这是不可能的。但是,您可以尝试先获取它们的值或检查它们是否存在:
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();
try{
return A[key1].Keys.Union(B[key1].Keys).ToList();
}
catch(KeyNotFoundException ex)
{}
任务是从 A[key1] 和 B[key1] 中找到所有的键并 "unite" 它们。 但是 A[key1] 和 B[key1] 可以抛出异常,我想知道我怎么知道是 A 对象还是 B 对象抛出了这些异常?
使用您发布的代码块,这是不可能的。但是,您可以尝试先获取它们的值或检查它们是否存在:
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();