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