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?
In general, it's good programming practice to catch a specific type of exception rather than use a basic catch statement. When an exception occurs, it is passed up the stack and each catch block is given the opportunity to handle it. The order of catch statements is important.
Exception Handling in Java is one of the effective means to handle the runtime errors so that the regular flow of the application can be preserved. Java Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.
With a solution open in Visual Studio, use Debug > Windows > Exception Settings to open the Exception Settings window. Provide handlers that respond to the most important exceptions. If you need to know how to add handlers for exceptions, see Fix bugs by writing better C# code.
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
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.
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