【发布时间】:2013-07-10 14:34:15
【问题描述】:
我有以下代码,当它试图抛出错误时,它给了我一个“用户代码未处理异常”:
private static void _msgQ_RecieveCompleted(object sender, ReceiveCompletedEventArgs e)
{
try
{
//queue that have received a message
MessageQueue _mq = (MessageQueue)sender;
//get the message off the queue
Message _mqmsg = _mq.EndReceive(e.AsyncResult);
throw new Exception("This is a test exception by Tim");
//set the values back into a formatted struct
//now process your SQL....
Azure_SQL _azuresql = new Azure_SQL();
_azuresql.writeMessageToStorage((_TwitterStreamFeed)_mqmsg.Body);
//refresh queue just in case any changes occurred (optional)
_mq.Refresh();
//tell MessageQueue to receive next message when it arrives
_mq.BeginReceive();
return;
}
catch
{
throw;
}
}
通过以下方法调用(以前是sn-p):
public void MSMQ_GetMessage(string _MQ_Path)
{
try
{
//set the correct message queue
MessageQueue _msgQ = new MessageQueue(_MQ_Path, QueueAccessMode.ReceiveAndAdmin);
//set the format of the message queue
_msgQ.Formatter = new XmlMessageFormatter(new Type[] { typeof(_TwitterStreamFeed) });
try
{
_msgQ.ReceiveCompleted += new ReceiveCompletedEventHandler(_msgQ_RecieveCompleted);
}
catch
{
throw;
}
IAsyncResult _result = _msgQ.BeginReceive();
_asyncList.Add(_result); // asyncList is a global variable of type System.Collections - > this allows the callback to remain open and therefore nit garbage collected while the async thread runs off on it's own
}
catch (Exception _ex)
{
throw new Exception("_msgQ_get Message threw the following error :- " + _ex);
}
catch
{
throw;
}
}
您能帮我理解为什么错误没有返回到ReceiveCompletedEventHandler 调用吗?我知道它在不同的线程上执行代码,但我从 MSDN 示例中不明白如何捕获异常。我期待异常返回到调用 try/catch 块。
【问题讨论】:
-
你是重新抛出异常,而不是处理它?
-
抱歉,但在您的代码截图中,您只是为您的事件订阅了一个处理程序。你不喜欢它。第二个 try/catch 块没有任何意义(除非您有自定义的事件添加/删除处理程序)。
-
您试图在错误的位置捕获异常。异常不会在您将处理程序注册到事件的行中引发,而是在该事件被触发(调用)的行中引发。上面的代码中没有显示这一行。
-
另外,所有这些
catch { throw; }位都没有任何作用,也没有做任何事情,应该被删除。 -
我猜有一个对应的
EndReceive,里面也有EndInvoke。在异步调用中,您会捕获EndInvoke中的异常,而不是BeginInvoke。
标签: c# exception-handling delegates try-catch msmq