There are several questions ( 1 , 2 , 3 , 4 , etc.) called "Why this exception did not hit." Unfortunately, none of these solutions work for me ... So I'm stuck with a really elusive exception.
I have a piece of code (.NET 4.0) that checks a large text file for numbers and digits. During testing, I got an exception at runtime:

Here you see a try-catch pattern with catchblock to throw an ArgumentOutOfRangeException. But at run time, the try block throws an ArgumentOutOfRangeException exception that does not get caught.
I read the C # language spec about the try-catch structure, and it says:
Locking a try statement can be achieved if a try statement is available.
So, in theory, the above code should catch an exception.
Then I thought that this could be due to the fact that this code works in the task (during the processing of the text file, I also want to update the interface so that I make it asynchronous). I searched and then found this answer by Jon Skeet. Basically, I suggest using Task.Wait in a try-catch block to catch any exceptions.
The problem I'm currently facing is that I cannot name Task.Wait, because it blocks the calling thread, which is my UI thread! Then I decided that I could create an additional tasklayer to wait for this 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 it still gives the same result ... Then I thought that it could be due to the fact that I'm not specific enough for my Exceptiontype. But the C # language specification says:
Some programming languages may support exceptions that cannot be represented as objects originating from System.Exception, although such exceptions can never be thrown by C # code.
So, if you do not use some fragmentary third-party API, you will always be fine when using Exception . So I found myself with John Skeet's suggested answer, which didn’t quite work for me. This is when I knew that I just had to stop trying ...
So does anyone know what is going on? And how can I fix this? I know that I can simply check if i is equal to or greater than text.Length , but understanding what is happening is more important than working code.