for example:
first step:bind UnhandledException event.
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
second step:
try
{
//at here,do asynchronous operation and throw a exception.
}
catch (Exception ex)
{
Console.WriteLine("error");
}
when the asynchronous operation throw a exception,the catch code it not called,just only the UnhandledException event is triggered,after end event called then exit application.
i want capture exception anything in catch statement and avoid exit application.
=======================================================
the asynchronous code is the asynchronous socket operation.in the socket asynchronous receive message event(BeginReceive,EndReceive),i throw a OverFlowException.
throw new OverflowException("chunk size too long.");
=============================================
you are right,now i capture the exception in asynchronous operation and passed it to original class(this means exception will throw on the same thread,that can try...catcy statement can was called)
An asynchronous task by default will operate in a different context from the one it was instantiated in. The try/catch block is therefore not effective in this case.
Think about it in the following way.
Worker worker = new HouseMaid();
try
{
worker.DoSomeWork();
}
catch(WorkerIsSickException ex)
{
worker.TakeMedicin();
worker.StopWorkingAndRestForAWhile();
}
Here we see that when the worker gets sick, the work process breaks and the exception will be handeled. However, when we do:
Worker worker = new HouseMaid();
try
{
Worker otherWorker = new HouseMaidHelper();
worker.DelegateWorkTo(otherWorker, CallBackWhenOTherWorkerIsDone);
worker.GoOnDoSomethingElse();
}
catch(WorkerIsSickException ex)
{
worker.TakeMedicin();
worker.StopWorkingAndRestForAWhile();
}
The work try/catch block (or safety net if you will), will only apply for the worker, not otherWorker. The otherWorker has its own scope to work in. If the other worker fails, that shouldnt mean that the worker has to take the medicine.
Your question isn't clear, but if it's the asynchronous operation which throws the exception, then the code you've shown could easily have completed before the exception is thrown anyway - it's all asynchronous, right?
Basically asynchrony makes you rethink error handling - and quite how you do it depends on your asynchrony approach. You'd often catch the exception in the callback - or not even catch it, but check for it with something like Task.Status.
Admittedly all the work in C# 5 for async stuff should make some of this easier, but you still need to think about the asynchrony.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With