I am querying a database and wrapping the results into a view model. Testing an intentionally erroneous connection string, an exception is thrown when the query executes at for (object result in query)
. According to my research (below) an exception should be handled by an external try/catch
block without adding async
as a keyword for the lambda. However, when I run the code without the async
keyword, the exception is not caught and the program crashes.
Why is my exception not being handled?
Note that the only change here is the addition of async
to the lambda expression for Task.Run
.
According to Stephen Cleary's comment on this answer an external try/catch
should catch an exception without async
.
I have confirmed that "Break When Thrown" is disabled
Update
From a comment, I tried Disabling "Just my Code"
It did allow the exception to be caught, but it still produced unusual behavior.
If you run the non-async example while "Just My Code" is disabled, the exception is thrown 15 times before returning to the catch block.
Exception not caught by external try/catch
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Data.Linq;
using System.Data.Linq.Mapping;
namespace ThisQuestion
{
class Program
{
static void Main(string[] args)
{
DoWork();
Console.ReadLine();
}
private async static void DoWork()
{
DataContext _db = new DataContext("badconnectionstring");
Table<Objects> objects = _db.GetTable<Objects>();
IQueryable<object> query =
from o in objects
select o;
try
{
await Task.Run
(() =>
{
foreach (object result in query) ;
});
}
catch (System.Data.SqlClient.SqlException)
{
System.Diagnostics.Debug.WriteLine("SQLError");
}
}
}
[Table(Name="Objects")]
class Objects
{
private string AColumn;
}
}
Exception caught by external try/catch
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Data.Linq;
using System.Data.Linq.Mapping;
namespace ThisQuestion
{
class Program
{
static void Main(string[] args)
{
DoWork();
Console.ReadLine();
}
private async static void DoWork()
{
DataContext _db = new DataContext("badconnectionstring");
Table<Objects> objects = _db.GetTable<Objects>();
IQueryable<object> query =
from o in objects
select o;
try
{
await Task.Run
(async () =>
{
foreach (object result in query) ;
});
}
catch (System.Data.SqlClient.SqlException)
{
System.Diagnostics.Debug.WriteLine("SQLError");
}
}
}
[Table(Name="Objects")]
class Objects
{
private string AColumn;
}
}
"Just My Code" Enabled, w/o async