使用委托,我正在调用返回 int 的对象(“o”)方法(“ProcessElement”):
int result;
object o;
...
if (o != null) {
try {
Func<int> processElement =
(Func<int>)Delegate.CreateDelegate(
typeof(Func<int>),
o,
"ProcessElement");
result = processElement();
} catch (Exception) {
throw;
}
}
在我遇到异常之前,这很好用。
当我遇到异常时,Visual Studio 会抛出一个错误,指出异常未处理。我有一个围绕代表的尝试/捕捉。这不应该捕获异常吗?
ProcessElement 方法:
public int ProcessElement () {
throw new ApplicationException("test");
}
视觉工作室错误:
ApplicationExcpetion was unhandled
谢谢,
编辑:也许我不是很清楚-对不起。我知道你不能复制和粘贴来测试,但无论如何,这里有更多的故事:
static void Main (string[] args) {
try {
Thread processThread = new Thread(ExecuteConfiguration);
processThread.Start();
if (!processThread.Join(TimeSpan.FromMilliseconds(int.Parse((_Configuration2.TimeOutMinutes * 60 * 1000).ToString())))) {
processThread.Abort();
Status = Program.BatchJobsStatus.TimeOut;
throw new ApplicationException("Time out");
}
} catch (Exception ex) {
//Expecting to catch error thrown in ExecuteConfiguration -> SendEmail here.
Logger.WriteErrorMessage("\n" + ex.ToString());
}
}
private static void ExecuteConfiguration () {
for (int i = 0; i < ElementCount; i++) {
if (ContinueProcessing) {
object o = GetConfigurationElementById(_Configuration2, "ElementId", i.ToString());
if (o != null) {
MethodInfo method = o.GetType().GetMethod("ProcessElement");
if (method != null) {
try {
Console.WriteLine("(ElementId " + i.ToString() + ") " + o.GetType().FullName);
Func<int> processElement = (Func<int>)Delegate.CreateDelegate(typeof(Func<int>), o, method);
i = processElement();
} catch (Exception) {
// rethrow error thrown in SendEmail
throw;
}
} else {
Console.WriteLine("(ElementId " + i.ToString() + ") " + o.GetType().FullName + " method ProcessElement does not exist");
}
}
}
}
}
public int ProcessElement () {
int result = ElementId;
SendEmail(); // error thrown here, resulting in "Exception was unhandled" error in calling method (ExecuteConfiguration)
for (int i = ElementId + 1; i < Program.ElementCount; i++) {
if (Program.ContinueProcessing) {
object o = Program.GetConfigurationElementById(this, "ElementId", i.ToString());
if (o != null) {
MethodInfo method = o.GetType().GetMethod("ProcessElement");
if (method != null) {
try {
Console.WriteLine("(ElementId " + i.ToString() + ") " + o.GetType().FullName);
Func<int> processElement = (Func<int>)Delegate.CreateDelegate(typeof(Func<int>), o, method);
result = processElement();
} catch (Exception) {
throw;
}
} else {
Console.WriteLine("(ElementId " + i.ToString() + ") " + o.GetType().FullName + " method ProcessElement does not exist");
result = i;
}
}
}
}
return result;
}
public void SendEmail() {
throw new ApplicationException("test");
}
我希望错误会冒泡到“主要”,因为这是我的顶级尝试/捕获,但事实并非如此。相反,我在“ExecuteConfiguration”中得到“ApplicationExcpetion 未处理”。