ExceptionTracerTest.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. * Copyright 2012-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <iostream>
  17. #include <stdexcept>
  18. #include <folly/experimental/exception_tracer/ExceptionTracer.h>
  19. // clang-format off
  20. [[noreturn]] void bar() {
  21. throw std::runtime_error("hello");
  22. }
  23. // clang-format on
  24. void dumpExceptions(const char* prefix) {
  25. std::cerr << "--- " << prefix << "\n";
  26. auto exceptions = ::folly::exception_tracer::getCurrentExceptions();
  27. for (auto& exc : exceptions) {
  28. std::cerr << exc << "\n";
  29. }
  30. }
  31. void foo() {
  32. try {
  33. try {
  34. bar();
  35. } catch (const std::exception& e) {
  36. dumpExceptions("foo: simple catch");
  37. bar();
  38. }
  39. } catch (const std::exception& e) {
  40. dumpExceptions("foo: catch, exception thrown from previous catch block");
  41. }
  42. }
  43. [[noreturn]] void baz() {
  44. try {
  45. try {
  46. bar();
  47. } catch (...) {
  48. dumpExceptions("baz: simple catch");
  49. throw;
  50. }
  51. } catch (const std::exception& e) {
  52. dumpExceptions("baz: catch rethrown exception");
  53. throw "hello";
  54. }
  55. }
  56. void testExceptionPtr1() {
  57. std::exception_ptr exc;
  58. try {
  59. bar();
  60. } catch (...) {
  61. exc = std::current_exception();
  62. }
  63. try {
  64. std::rethrow_exception(exc);
  65. } catch (...) {
  66. dumpExceptions("std::rethrow_exception 1");
  67. }
  68. }
  69. void testExceptionPtr2() {
  70. std::exception_ptr exc;
  71. try {
  72. throw std::out_of_range("x");
  73. } catch (...) {
  74. exc = std::current_exception();
  75. }
  76. try {
  77. std::rethrow_exception(exc);
  78. } catch (...) {
  79. dumpExceptions("std::rethrow_exception 2");
  80. }
  81. }
  82. int main(int /* argc */, char* /* argv */ []) {
  83. foo();
  84. testExceptionPtr1();
  85. testExceptionPtr2();
  86. baz();
  87. // no return because baz() is [[noreturn]]
  88. }