Idov
Idov

Reputation: 5124

c++ try-except statement

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 :)

Upvotes: 4

Views: 3314

Answers (5)

Praetorian
Praetorian

Reputation: 109119

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.

Upvotes: 1

dascandy
dascandy

Reputation: 7292

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.

Upvotes: 1

Ameer
Ameer

Reputation: 2638

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.

Upvotes: 2

Puppy
Puppy

Reputation: 146910

__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.

Upvotes: 6

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385104

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.

Upvotes: 2

Related Questions