应该使用哪种异常处理
-
结构化异常是操作系统提供的处理异常的方式,因此结构化异常不局限于处理C++语言的异常。
-
C++异常是处理C++语言的异常方式,当编译器识别出所要处理的异常是C++异常时,会针对C++语言特性做异常处理,比如局部类实例的析构等操作。
-
如果编译器是Windows的VS,则会将C++异常转化为结构化异常的一种特殊形式,VS编译器会在编译阶段将C++异常的try catch转化为_try _except,将throw转化为RaiseException()。
-
因此,相当于我们使用C++异常时,是告知编译器异常处理类型为C++异常,同时编译器将C++异常转化成操作系统的结构化异常来做底层实现。
-
C++异常被转化成结构化异常后,dwExceptionCode=0xE06D7363,其中6D 73 63的ASCII码为“msc”。
-
C++异常不能够处理可恢复异常处理情况,此时需要使用结构化异常来解决,因为结构化异常可以EXCEPTION_CONTINUE_EXECUTION。
-
使用VS编译程序时,当使用try catch处理异常时,需要注意编译选项的设置:
- /EHa[-] :Enables standard C++ stack unwinding. Catches both structured (asynchronous) and standard C++ (synchronous) exceptions when you use catch(…) syntax. /EHa overrides both /EHs and /EHc arguments.
- /EHs[-] :Enables standard C++ stack unwinding. Catches only standard C++ exceptions when you use catch(…) syntax. Unless /EHc is also specified, the compiler assumes that functions declared as extern “C” may throw a C++ exception.
- /EHc[-] :When used with /EHs, the compiler assumes that functions declared as extern “C” never throw a C++ exception. It has no effect when used with /EHa (that is, /EHca is equivalent to /EHa). /EHc is ignored if /EHs or /EHa aren’t specified.
- /EHr[-] :Tells the compiler to always generate runtime termination checks for all noexcept functions. By default, runtime checks for noexcept may be optimized away if the compiler determines the function calls only non-throwing functions. This option gives strict C++ conformance at the cost of some extra code. /EHr is ignored if /EHs or /EHa aren’t specified.