PaulH
PaulH

Reputation: 7873

Why catch an Access Violation?

Unlike C++ exceptions, an Access Violation indicates your applications runtime is compromised and the state of your application is, therefore, undefined. The best thing to do in that circumstance is to exit your application (generally done for you because it crashes).

I note that it is possible to catch one of these exceptions. In Microsoft Visual C++, for example, you can use /EHa or __try/__catch to do so.

So, what are the reasons you would want to catch them? As I understand it, there's no way for your application to recover.

Upvotes: 3

Views: 940

Answers (5)

tenfour
tenfour

Reputation: 36906

Your app is not guaranteed to be stable after all access violations. But it can be stable or recover after some, so catching the access violation gives you the opportunity to:

  1. Inform the user something went bad
  2. Let the user attempt to save work
  3. Attempt to recover
  4. Log diagnostic information
  5. Exit in the way you want, rather than disappearing.

A typical example of this is a host application that catches exceptions from a plugin. This way the host app (Photoshop, for example) can tell the user that "Plugin X crashed, and Photoshop is unstable... you should save your work, and restart Photoshop."

Note that this is different than C++ exception handling, which does not indicate unrecoverable errors at all, but is more of a stack unwinding feature.

Upvotes: 3

Dave Rager
Dave Rager

Reputation: 8160

If your application gets an access violation you may or may not be able to recover. If your application is left in an undefined state, you clobber your stack for instance, you're done.

Read from a runaway pointer probably won't corrupt your application and from that you likely can recover.

Either way, the fact that it is occurring indicates a bug in your code so instead of trying to recover you should catch the error and dump what state you can to help you debug the problem.

Upvotes: 1

Mark Wilkins
Mark Wilkins

Reputation: 41262

One reason might be to write a crash dump file; you would have more control over it and be able to write the exact type you wanted. In Windows, for example, you could call MiniDumpWriteDump to do this.

Upvotes: 6

Drise
Drise

Reputation: 4388

I think it would be better to gracefully crash and let the user know what's going on, rather than just having the application disappear.

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490728

You can recover from an access violation.

For example, you can create a dynamic array by allocating some address space with VirtualAlloc, but marking the memory it points at as not-present. Then, when you attempt to use some memory, you catch the access violation, map a page of memory where the access took place, then re-try the instruction that caused the violation.

Upvotes: 8

Related Questions