c++ try-except statement

◇◆丶佛笑我妖孽 提交于 2019-12-30 23:04:24

问题


I came across this article about detecting VMWare or Virtual PC
http://www.codeproject.com/KB/system/VmDetect.aspx
and I saw that they use some kind of try-except statement.
So I looked it up in the MSDN: http://msdn.microsoft.com/en-us/library/s58ftw19%28v=vs.80%29.aspx

and I don't understand why would I use a try-except instead of the good old try-catch. does it just give me additional information about the exception?
If so, I can use a try-catch when I use the code from the attached article, right?
thanks :)


回答1:


__try/__except is a try/catch, for a different kind of exception. You can catch hardware exceptions like floating point violation, bad pointer de-reference, etc, and not C++ exceptions. This is referred to as Structured Exception Handling, or SEH, and MSDN has quite a bit on it if you know where to look.

In this case, they're using it to detect invalid instructions. This is where they attempt to execute instructions that x86 doesn't support, and virtual machines use them. If you're running on a real CPU, then you will get an invalid instruction exception, and if you're running on a virtual machine, you just talked to it.




回答2:


MSDN is typically unclear about all of this, but the exceptions dealt with by __try/__except are not C++ exceptions, but system exceptions. Things like Segmentation Fault.




回答3:


the __try and __except are part of structured exception handling, this is a different exception handling model than the standard one, as it handles hardware exceptions identically to software ones, see the link for information.




回答4:


Microsoft created Structured Exception Handling for Microsoft C++ before the actual C++ standard started to include exceptions as well. On Windows, therefore, all exceptions that exist are SEH exceptions, but not all of those are C++ exceptions.

__try / __except is a way to catch SEH exceptions (and accidentally, also C++ exceptions). try/catch is the way to catch only C++ exceptions. I also recall that there's a limit to not being able to use both in one function, but it's easy to work around that.

For use, just use try/catch for any exceptions. If somebody explicitly throws you a SEH exception (divide by zero, null pointer dereference etc.), catch it and convert it to regular program flow asap, such as making it into a regular exception or halting the software.




回答5:


The __try, __except and __finally clauses are for Structured Exception Handling, this is an exception handling mechanism for exceptions thrown by Windows. They're not the same as C++ exceptions.



来源:https://stackoverflow.com/questions/6600507/c-try-except-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!