Shift the exception tracer benchmark and test into the test directory
[folly.git] / folly / experimental / exception_tracer / test / ExceptionTracerTest.cpp
1 /*
2  * Copyright 2017-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
19 #include <folly/experimental/exception_tracer/ExceptionTracer.h>
20
21 [[noreturn]] void bar() {
22   throw std::runtime_error("hello");
23 }
24
25 void dumpExceptions(const char* prefix) {
26   std::cerr << "--- " << prefix << "\n";
27   auto exceptions = ::folly::exception_tracer::getCurrentExceptions();
28   for (auto& exc : exceptions) {
29     std::cerr << exc << "\n";
30   }
31 }
32
33 void foo() {
34   try {
35     try {
36       bar();
37     } catch (const std::exception& e) {
38       dumpExceptions("foo: simple catch");
39       bar();
40     }
41   } catch (const std::exception& e) {
42     dumpExceptions("foo: catch, exception thrown from previous catch block");
43   }
44 }
45
46 [[noreturn]] void baz() {
47   try {
48     try {
49       bar();
50     } catch (...) {
51       dumpExceptions("baz: simple catch");
52       throw;
53     }
54   } catch (const std::exception& e) {
55     dumpExceptions("baz: catch rethrown exception");
56     throw "hello";
57   }
58 }
59
60 void testExceptionPtr1() {
61   std::exception_ptr exc;
62   try {
63     bar();
64   } catch (...) {
65     exc = std::current_exception();
66   }
67
68   try {
69     std::rethrow_exception(exc);
70   } catch (...) {
71     dumpExceptions("std::rethrow_exception 1");
72   }
73 }
74
75 void testExceptionPtr2() {
76   std::exception_ptr exc;
77   try {
78     throw std::out_of_range("x");
79   } catch (...) {
80     exc = std::current_exception();
81   }
82
83   try {
84     std::rethrow_exception(exc);
85   } catch (...) {
86     dumpExceptions("std::rethrow_exception 2");
87   }
88 }
89
90 int main(int /* argc */, char* /* argv */ []) {
91   foo();
92   testExceptionPtr1();
93   testExceptionPtr2();
94   baz();
95   // no return because baz() is [[noreturn]]
96 }