Home >Backend Development >C++ >When and Why Should You Utilize the __try Keyword in C ?

When and Why Should You Utilize the __try Keyword in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-06 13:16:02797browse

When and Why Should You Utilize the __try Keyword in C  ?

C Try/Catch/Finally Blocks and the __try Keyword

Structured Exception Handling (SEH) is the operating system-level exception handling mechanism supported by Windows. Compilers for Windows typically utilize SEH to implement C exceptions.

While the C keywords throw and catch exclusively handle C exceptions, Microsoft Visual C (MSVC) compiler provides non-standard __try and __except keywords to handle SEH exceptions.

__try Block:

The non-standard __try block defines the scope where an exception can occur, just like a try block in C . It's followed by __except and __finally blocks.

__except Block:

The __except block is similar to a catch block in C but offers more flexibility. It has an exception filter expression that evaluates whether an active exception should be handled.

__finally Block:

The __finally block contains code that runs after any exception handling. It's similar to a finally block in C#, but not directly equivalent in standard C .

Use Case for __try Blocks:

SEH exceptions can include those generated by the operating system, interoperating code using SEH, or managed code using the ".NET" exception code. To catch these exceptions in C , __try blocks must be used along with __except blocks.

Example Program:

The example program demonstrates SEH exceptions and how C destructors can be called during SEH exception unwinding.

#include <windows.h>
#include <iostream>

class Example {
public:
  ~Example() { std::cout << "destructed" << std::endl; }
};

int filterException(int code, PEXCEPTION_POINTERS ex) {
  std::cout << "Filtering " << std::hex << code << std::endl;
  return EXCEPTION_EXECUTE_HANDLER;
}

int main() {
  __try {
    Example e;
    int* p = 0;
    *p = 42;  // intentially generating a processor fault
  } __except (filterException(GetExceptionCode(), GetExceptionInformation())) {
    std::cout << "caught" << std::endl;
  }

  return 0;
}

Output:

Filtering c0000005
destructed
caught

The above is the detailed content of When and Why Should You Utilize the __try Keyword in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn