I have the following code which gives me an "Exception was unhandled by user code" when it tries to throw an error:
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;
}
}
It is called by the following method (previously the snippet):
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;
}
}
Can you help me understand why the error isn't thrown back to the ReceiveCompletedEventHandler
call? I get that it's executing the code on a different thread, but I don't understand from the MSDN examples how to capture the exception. I was expecting the Exception to be return to the call try/catch block.
Here are four approaches.
In approach "A", the Exception is multi-cast to all subscribers. This is done by including the Exception instance as an "innerException" field in your custom EventArgs class.
In approach "B", the Exception is handled "out-of-band" (not multi-cast, not part of the event mechanism) by calling a separate delegate.
In approach "C", you have an application-level exception handler. You want to inform it that this exception happened as part of processing ReceiveCompleted. Do this by defining (and throwing) a ReceiveCompletedException, which has an "innerException" field to contain the actual exception.
In approach "D" (no code given below) you don't care that the exception happened in ReceiveCompleted code. You just need a generic place to handle exceptions. This is known as "application-level exception handling". See Catch-all error handling on application level?
Approach A:
Approach B:
Approach C: