SE.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /*
  2. * Copyright: JessMA Open Source (ldcsaa@gmail.com)
  3. *
  4. * Version : 2.3.15
  5. * Author : Bruce Liang
  6. * Website : http://www.jessma.org
  7. * Project : https://github.com/ldcsaa
  8. * Blog : http://www.cnblogs.com/ldcsaa
  9. * Wiki : http://www.oschina.net/p/hp-socket
  10. * QQ Group : 75375912
  11. *
  12. * Licensed under the Apache License, Version 2.0 (the "License");
  13. * you may not use this file except in compliance with the License.
  14. * You may obtain a copy of the License at
  15. *
  16. * http://www.apache.org/licenses/LICENSE-2.0
  17. *
  18. * Unless required by applicable law or agreed to in writing, software
  19. * distributed under the License is distributed on an "AS IS" BASIS,
  20. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21. * See the License for the specific language governing permissions and
  22. * limitations under the License.
  23. */
  24. /******************************************************************************
  25. Module: SE.h
  26. Notices: Copyright (c) 2006 Bruce Liang
  27. Purpose: 把结构化异常转换成 C++ 异常.
  28. Desc:
  29. 1. 用 C++ 方式处理结构化异常
  30. Usage:
  31. 1. 项目 -> 配置属性 -> C/C++ -> 代码生成 -> 启用 C++ 异常选择"否"
  32. 2. 项目 -> 配置属性 -> C/C++ -> 命令行 -> 加入 "/EHac"
  33. 3. 在每个线程的入口处调用: MapSEx2CppEx()
  34. 4. 在要处理结构化异常的地方使用 try{...} catch(CSE se){...}
  35. Rule:
  36. Example: 1. 见: TestSE 测试程序
  37. 2. 下面的代码片断
  38. void ThreadFunc(PVOID pv)
  39. {
  40. // Must be called before any exceptions are raised
  41. MapSEx2CppEx();
  42. try
  43. {
  44. *(PBYTE)0 = 0; // Accesss violation
  45. int x = 0;
  46. x = 5 / x; // Division by zero
  47. }
  48. catch(CSE& se)
  49. {
  50. switch(se)
  51. {
  52. case EXCEPTION_ACCESS_VIOLATION:
  53. // This code handles an access-violation exception
  54. break;
  55. case EXCEPTION_INT_DIVIDE_BY_ZERO:
  56. // This code handles a division-by-zero exception
  57. break;
  58. default:
  59. // We don't handle any other exceptions;
  60. throw;
  61. }
  62. }
  63. }
  64. ******************************************************************************/
  65. #pragma once
  66. #include <eh.h>
  67. #define MapSEx2CppEx() CSE::MapSE2CE()
  68. class CSE
  69. {
  70. public:
  71. // 结构化异常转换成 C++ 异常.
  72. static void MapSE2CE() {_set_se_translator(TranslateSE2CE);}
  73. operator DWORD() {return m_er.ExceptionCode;}
  74. CSE(PEXCEPTION_POINTERS pep)
  75. : m_er(*pep->ExceptionRecord)
  76. , m_context(*pep->ContextRecord)
  77. {
  78. }
  79. static void _cdecl TranslateSE2CE(UINT ec, PEXCEPTION_POINTERS pep) {throw CSE(pep);}
  80. private:
  81. EXCEPTION_RECORD m_er; // CPU independent exception informaiton
  82. CONTEXT m_context; // CPU dependent exception informaiton
  83. };