There are multiple questions (1,2,3,4 etc. etc.) called "Why isn't this exception caught". Sadly, none of these solutions work for me... So I am stuck with a truly uncatchable exception.
I have a piece of code (.NET 4.0) that checks a large textfile for digits and numbers. Whilst testing I got a runtime exception:
What you see here is a try-catch pattern with a catchblock for an ArgumentOutOfRangeException. But during runtime, the try block throws an ArgumentOutOfRangeException that is not being caught.
I read the C# language specification section about the try-catch structure, and it says:
A catch block of a try statement is reachable if the try statement is reachable.
So in theory the above code should catch the exception.
Then I thought it might had something to do with the fact that this code is running in a task (during the processing of the textfile I also want to update the UI so I do it asynchronous). I searched around and then I found this answer by Jon Skeet. Basically suggesting I use Task.Wait in a try-catch block to catch any exceptions.
The problem I am facing now is that I can't really call Task.Wait because that would block the calling thread which is my UI thread! Then I figured that I could create an extra tasklayer to wait for that task:
//Code called from the UI
System.Threading.Tasks.Task.Factory.StartNew(()=>
{
//Create a new task and use this task to catch any exceptions
System.Threading.Tasks.Task task = System.Threading.Tasks.Task.Factory.StartNew(MethodWithException);
try
{
task.Wait();
}
catch(Exception)
{
MessageBox.Show("Caught it!");
}
});
But this still gives the same result... Then I thought that it could be because of the fact I am not specific enough with my Exceptiontype. But the C# Language Specification states:
Some programming languages may support exceptions that are not representable as an object derived from System.Exception, although such exceptions could never be generated by C# code.
So unless you use some sketchy third party API you're always good when you use Exception
. So I found myself with an suggested answer by Jon Skeet that didn't quite work for me. That's when I knew I should just stop trying...
So does anyone know what is going on? And how can I fix this? I know I could just check if i
is equal or bigger than text.Length
but understanding what's happening is more important than working code.