__try and __exception portability

早过忘川 提交于 2019-12-11 03:42:14

问题


Hello and excuse me again

I am reading "Detecting Multiprocessor Topology in IA-32 Architecture" from Intel. I was recoding the example. However I read this sentences __try and __except in the code.

I found MSDN Microsoft web page some information but I am using gcc compiler/linker

are __try and __except valid sentences in gcc? are __try and __except portable sentences on *nux environments? do exist a better mode than __try and __except sentences for exception handling in C?

Thanks in advance.


回答1:


General considerations

According to MSDN, __try and __except are extensions to the C language. As such, they are not portable out of the box.

For some applications it might be possible to mimic their behaviour using macros and a setjmp/longjmp constructs. In general this will not be the case. In particular, MSDN states that

The __except expression executes in the scope of the __try body.

which cannot be achieved using macros alone.

Your questions

are __try and __except valid sentences in gcc?

No, they are not, as gcc does not support this Microsoft dialect of C.

are __try and __except portable sentences on *nux environments?

No, they are not, although there are ways to achieve similar exception handling on *nix as well.

do exist a better mode than __try and __except sentences for exception handling in C?

There is a strong reason to use C++ when you do exception handling. C++ scoped objects with destructors are much more robust in the presence of exceptions than standard C resource management. So while there are implementations which provide tryand catch for C one way or another, I'd advise against them and favor C++ instead. Exception handling in C++ is part of the standard and therefore supported by all standards-compliant compilers, without portability issues.




回答2:


C standard has no exception handling support. C++ does. There are a number of try/catch implementations using setjmp.




回答3:


The __try and __except is (as Microsoft states) an extension to the C/C++ language. So it is not portable in gcc. I think Microsoft put these in so that pure C (not using a C++ compiler) could have something similar to exception handling. *S*tructured *E*xception *H*andling (SEH) is pretty low level, and as far as I can remember even Microsoft's own C++ exception handling uses SEH under the hood.

My take on the whole thing is, if you are see __try and __except, just replace it with try and catch, and just compile with a C++ compiler. You will of course have to replace the filter that gets passed to __except, but that's not a big deal.




回答4:


You might want to take a look at the following links:

gcc.gnu.org/onlinedocs/libstdc++/manual/using_exceptions.html

www.autohotkey.com/community/viewtopic.php?t=31475



来源:https://stackoverflow.com/questions/12513209/try-and-exception-portability

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