Sean
Sean

Reputation: 2119

Can a try/catch block prevent an error from occuring?

I have some code in my application that throws an error every so often (System.AccessViolationException) - So I wrapped it in a try/catch block and set a debug point and logging method in the catch element. I've found that since I did this the error has stopped happening - the debug point is never hit and nothing is logged. As soon as I remove the try from around the code I get the error again. What could be causing this?

The code is pretty trivial:

 try
        {
            var f1 = new ResizeNearestNeighbor(lfu.Width, lfu.Height);
            var f2 = new Crop(ViewRectangle);
            lfu = f2.Apply(lfu);
            lfu = f1.Apply(lfu);
        }
        catch (Exception ex)
        {
            MainForm.LogExceptionToFile(ex);//never hit
        }

Upvotes: 0

Views: 124

Answers (2)

Tigran
Tigran

Reputation: 62265

There could be a couple of options:

  • or MainForm.LogExceptionToFile(ex); does not work as it expected

  • or, if we are 100% sure in that method, probably injecting try/catch block introduces in the code flow that microscopic delay (due the more IL code to execute/control), which is necessary to not get AccessViolationException on that machine. Which means, that is absolutely possible that you will get that exception on some other machine.

Upvotes: 1

user2463711
user2463711

Reputation:

A AccessViolation Exception can't be skipped or catched.

Every time this exception happens it would be thrown!

Upvotes: 0

Related Questions