0

I am writing a Windows-specific library in C and am considering the use of try-finally statements, a Microsoft extension to the C language, to streamline my code for cleaning up resources even in cases of unexpected failures. An example is given in Cleaning up resources.

I am not concerned about OS portability and with regard to compiler portability, the current version of Clang appears to support it on Windows as well.

The only negative consequence I have identified so far is potential interference with standard C++ exception handling. A detailed explanation of this can be found in the documentation pages Handle structured exceptions in C++ and /EH (Exception handling model). The situation seems safe for .NET languages, but I am concerned that C++ users may not set the right compiler option and possibly experience inconveniences like the one documented in this SO answer.

Is this a valid concern? Are there any other drawbacks or reasons to reconsider the use of try-finally statements?

Reinier Torenbeek
  • 16,669
  • 7
  • 46
  • 69
  • 2
    `__try`/`__finally` are meant to be used with SEH exclusively. They aren't general purpose cleanup hooks. Internally they introduce code to set up exception handling frames (x86) or add entries to the exception handler dispatch tables (x64). If you need to perform cleanup in C it's common to use named labels and `goto`s. Alternatively use C++ for your implementation and expose a C interface. C++' destructors enable streamlined RAII implementations. – IInspectable Sep 21 '20 at 10:18
  • @IInspectable thanks, I am interested in performance penalties. However, I read that MSVC builds its C++ exception handling support on top of SEH and that using C++ exceptions should not incur a performance penalty unless an exception is actually raised. Those both seem to contradict your comment (which imo deserves upgrading to an answer). – Reinier Torenbeek Sep 21 '20 at 15:11
  • 1
    You'll find lots of contradicting information on this, primarily because MSVC implements SEH differently for x86 and x64 (I don't know how SEH is implemented for other architectures). In case of x86 MSVC inserts instructions unconditionally. Even if no exception is raised that code needs to execute. Though cheap, it still uses up precious stack memory. x64 uses table-based EH; the non-throwing path has zero code overhead, but EH is expensive. Plus, the tables are a main contributor to increased binary sizes for x64 builds, which can adversely affect runtime performance as well. – IInspectable Sep 21 '20 at 15:30

0 Answers0