简体   繁体   English

捕获c ++“访问冲突写入异常”?

[英]Catching c++ “Access Violation Writing Exception”?

In my c++ code, I have a block of code that gives me an "Access Violation Writing Location ..." Exception when user input is invalid.. 在我的c ++代码中,我有一段代码,它给我一个“访问冲突写入位置...”当用户输入无效时的例外。

I tried to catch this exception in my try/catch block to display error message when the exception occurs.. but for some reason it is not catching the error. 我试图在我的try / catch块中捕获此异常,以便在发生异常时显示错误消息..但由于某种原因它没有捕获错误。

try {
    // ... some code that causes Access Violation Writing Location Exception
}
catch (...) {
    std::cout << "invalid user input" << endl;
}

I did this, but when the exception occurs, the console does not display my error message, but says there is an 我这样做了,但是当异常发生时,控制台不会显示我的错误消息,但是说有一个

Unhandled exception at 0x0F0B0E9A (msvcr110d.dll) in Example.exe : Access violation writing location

So it seems like my try/catch block is not catching the exception... 所以看起来我的try / catch块没有捕获异常......

I set break points to make sure that the exception is occuring within the try block.. and I'm 100% that's the case.. 我设置了断点以确保在try块中发生异常..而且我100%就是这种情况..

Why is "catch (...)" not catching the Access Violation exception? 为什么“catch(...)”没有捕获Access Violation异常?

Don't do this! 不要这样做!

An access violation is not a C++ exception. 访问冲突不是C ++异常。 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. 的,有处理访问冲突的一种方式,但正如我前面所说,这不是正确的解决您的问题,所以我认为没有理由来阐述就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM