Catching c++ “Access Violation Writing Exception”?

后端 未结 1 1263
广开言路
广开言路 2021-01-18 18:42

In my c++ code, I have a block of code that gives me an \"Access Violation Writing Location ...\" Exception when user input is invalid..

I tried to catch this except

相关标签:
1条回答
  • 2021-01-18 19:23

    Don't do this!

    An access violation is not a C++ exception. It is the operating system trying to terminate the application because it did something invalid.

    Specifically, it tried to write to a memory address it did not have the privileges to access. This basically means you're writing to random memory, which means that even if you did catch this error and showed a nice error message to the user, it might not always work. Sometimes, instead of writing to memory that you don't have write permissions for, the program might end up writing over other parts of your program. That won't raise an access violation, so the problem won't be detected. It will just corrupt your program.

    The only correct way to do this is to validate your user input. You have to check that the user input is in a form that your program can handle safely. If it isn't, you have to either correct it, or abort, and show an error to the user. You have to do that in your own code, before your application does something so bad that the OS is forced to try to terminate it.

    Yes, there is a way to handle Access Violations, but as I said above, that is not the correct solution to your problem, so I see no reason to elaborate on it.

    0 讨论(0)
提交回复
热议问题