Reputation: 26434
I studied this article on MSDN, as well as some questions/answers on SO regarding this topic, but cannot figure why below code does not work (in a sample console app).
AggregateException is expected to be thrown, according to MSDN, which would contain one inner exception with hello
message. Instead, this hello
exception is unhandled. It happens when inside a debugger.
If you press continue or run standalone, it works as expected. Is there any way to avoid pressing continue all the time in VS? After all, whatever is within a Try...Catch
block is considered handled in a single threaded programming model. Otherwise, debugging could be a nightmare.
VB.NET
Sub Main()
Try
Task.Factory.StartNew(AddressOf TaskThatThrowsException).Wait()
Catch ex As AggregateException
Console.WriteLine(ex.ToString) 'does not get here until you hit Continue
End Try
End Sub
Private Sub TaskThatThrowsException()
Throw New Exception("hello") 'exception was unhandled
End Sub
C#
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
try {
Task.Factory.StartNew(TaskThatThrowsException).Wait();
}
catch (AggregateException ex) {
Console.WriteLine(ex.ToString()); //never gets here
}
}
static void TaskThatThrowsException() {
throw new Exception("hello"); //exception was unhandled
}
}
}
Is there something obvious I am missing here?
Upvotes: 8
Views: 2596
Reputation: 17444
The setting "Enable Just My Code" has an effect on this. Under Tools->Options, Debugging->General->enable Just My Code. If you have it turned on, it will consider the exception unhandled if your code doesn't handle it. Try turning this option off.
See: http://msdn.microsoft.com/en-us/library/dd997415.aspx
Upvotes: 2
Reputation: 244948
This is most likely because you're misunderstanding what the Visual Studio dialog is saying.
The exception is “user unhandled”, because there is no user code that catches it (the original Exception
), it's catched by TPL. So, if you let the debugger continue, or if you run your application without the debugger, you will see the behavior you're expecting.
Upvotes: 2