fa91d45870ad1ac9ad3f4c5a812e5499d71b9f18
[folly.git] / folly / ExceptionWrapper.h
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 /*
17  * Author: Eric Niebler <eniebler@fb.com>
18  */
19
20 #pragma once
21
22 #include <cassert>
23 #include <cstdint>
24 #include <exception>
25 #include <iosfwd>
26 #include <memory>
27 #include <new>
28 #include <type_traits>
29 #include <typeinfo>
30 #include <utility>
31
32 #include <folly/Assume.h>
33 #include <folly/CPortability.h>
34 #include <folly/Demangle.h>
35 #include <folly/ExceptionString.h>
36 #include <folly/FBString.h>
37 #include <folly/Traits.h>
38
39 #ifdef __GNUC__
40 #pragma GCC diagnostic push
41 #pragma GCC diagnostic ignored "-Wpragmas"
42 #pragma GCC diagnostic ignored "-Wpotentially-evaluated-expression"
43 // GCC gets confused about lambda scopes and issues shadow-local warnings for
44 // parameters in totally different functions.
45 #pragma GCC diagnostic ignored "-Wshadow-local"
46 #pragma GCC diagnostic ignored "-Wshadow-compatible-local"
47 #endif
48
49 #define FOLLY_EXCEPTION_WRAPPER_H_INCLUDED
50
51 namespace folly {
52
53 #define FOLLY_REQUIRES_DEF(...) \
54   _t<std::enable_if<static_cast<bool>(__VA_ARGS__), long>>
55
56 #define FOLLY_REQUIRES(...) FOLLY_REQUIRES_DEF(__VA_ARGS__) = __LINE__
57
58 namespace exception_wrapper_detail {
59
60 template <template <class> class T, class... As>
61 using AllOf = StrictConjunction<T<As>...>;
62
63 template <bool If, class T>
64 using AddConstIf = _t<std::conditional<If, const T, T>>;
65
66 template <class Fn, class A>
67 FOLLY_ALWAYS_INLINE FOLLY_ATTR_VISIBILITY_HIDDEN
68 auto fold(Fn&&, A&& a) {
69   return static_cast<A&&>(a);
70 }
71
72 template <class Fn, class A, class B, class... Bs>
73 FOLLY_ALWAYS_INLINE FOLLY_ATTR_VISIBILITY_HIDDEN
74 auto fold(Fn&& fn, A&& a, B&& b, Bs&&... bs) {
75   return fold(
76       // This looks like a use of fn after a move of fn, but in reality, this is
77       // just a cast and not a move. That's because regardless of which fold
78       // overload is selected, fn gets bound to a &&. Had fold taken fn by value
79       // there would indeed be a problem here.
80       static_cast<Fn&&>(fn),
81       static_cast<Fn&&>(fn)(static_cast<A&&>(a), static_cast<B&&>(b)),
82       static_cast<Bs&&>(bs)...);
83 }
84
85 } // namespace exception_wrapper_detail
86
87 //! Throwing exceptions can be a convenient way to handle errors. Storing
88 //! exceptions in an `exception_ptr` makes it easy to handle exceptions in a
89 //! different thread or at a later time. `exception_ptr` can also be used in a
90 //! very generic result/exception wrapper.
91 //!
92 //! However, there are some issues with throwing exceptions and
93 //! `std::exception_ptr`. These issues revolve around `throw` being expensive,
94 //! particularly in a multithreaded environment (see
95 //! ExceptionWrapperBenchmark.cpp).
96 //!
97 //! Imagine we have a library that has an API which returns a result/exception
98 //! wrapper. Let's consider some approaches for implementing this wrapper.
99 //! First, we could store a `std::exception`. This approach loses the derived
100 //! exception type, which can make exception handling more difficult for users
101 //! that prefer rethrowing the exception. We could use a `folly::dynamic` for
102 //! every possible type of exception. This is not very flexible - adding new
103 //! types of exceptions requires a change to the result/exception wrapper. We
104 //! could use an `exception_ptr`. However, constructing an `exception_ptr` as
105 //! well as accessing the error requires a call to throw. That means that there
106 //! will be two calls to throw in order to process the exception. For
107 //! performance sensitive applications, this may be unacceptable.
108 //!
109 //! `exception_wrapper` is designed to handle exception management for both
110 //! convenience and high performance use cases. `make_exception_wrapper` is
111 //! templated on derived type, allowing us to rethrow the exception properly for
112 //! users that prefer convenience. These explicitly named exception types can
113 //! therefore be handled without any peformance penalty. `exception_wrapper` is
114 //! also flexible enough to accept any type. If a caught exception is not of an
115 //! explicitly named type, then `std::exception_ptr` is used to preserve the
116 //! exception state. For performance sensitive applications, the accessor
117 //! methods can test or extract a pointer to a specific exception type with very
118 //! little overhead.
119 //!
120 //! \par Example usage:
121 //! \par
122 //! \code
123 //! exception_wrapper globalExceptionWrapper;
124 //!
125 //! // Thread1
126 //! void doSomethingCrazy() {
127 //!   int rc = doSomethingCrazyWithLameReturnCodes();
128 //!   if (rc == NAILED_IT) {
129 //!     globalExceptionWrapper = exception_wrapper();
130 //!   } else if (rc == FACE_PLANT) {
131 //!     globalExceptionWrapper = make_exception_wrapper<FacePlantException>();
132 //!   } else if (rc == FAIL_WHALE) {
133 //!     globalExceptionWrapper = make_exception_wrapper<FailWhaleException>();
134 //!   }
135 //! }
136 //!
137 //! // Thread2: Exceptions are ok!
138 //! void processResult() {
139 //!   try {
140 //!     globalExceptionWrapper.throwException();
141 //!   } catch (const FacePlantException& e) {
142 //!     LOG(ERROR) << "FACEPLANT!";
143 //!   } catch (const FailWhaleException& e) {
144 //!     LOG(ERROR) << "FAILWHALE!";
145 //!   }
146 //! }
147 //!
148 //! // Thread2: Exceptions are bad!
149 //! void processResult() {
150 //!   globalExceptionWrapper.handle(
151 //!       [&](FacePlantException& faceplant) {
152 //!         LOG(ERROR) << "FACEPLANT";
153 //!       },
154 //!       [&](FailWhaleException& failwhale) {
155 //!         LOG(ERROR) << "FAILWHALE!";
156 //!       },
157 //!       [](...) {
158 //!         LOG(FATAL) << "Unrecognized exception";
159 //!       });
160 //! }
161 //! \endcode
162 class exception_wrapper final {
163  private:
164   struct AnyException : std::exception {
165     std::type_info const* typeinfo_;
166     template <class T>
167     /* implicit */ AnyException(T&& t) noexcept : typeinfo_(&typeid(t)) {}
168   };
169
170   template <class Fn>
171   struct arg_type2_;
172   template <class Fn, class = void>
173   struct arg_type_;
174   template <class Fn>
175   using arg_type = _t<arg_type_<Fn>>;
176
177   // exception_wrapper is implemented as a simple variant over four
178   // different representations:
179   //  0. Empty, no exception.
180   //  1. An small object stored in-situ.
181   //  2. A larger object stored on the heap and referenced with a
182   //     std::shared_ptr.
183   //  3. A std::exception_ptr, together with either:
184   //       a. A pointer to the referenced std::exception object, or
185   //       b. A pointer to a std::type_info object for the referenced exception,
186   //          or for an unspecified type if the type is unknown.
187   // This is accomplished with the help of a union and a pointer to a hand-
188   // rolled virtual table. This virtual table contains pointers to functions
189   // that know which field of the union is active and do the proper action.
190   // The class invariant ensures that the vtable ptr and the union stay in sync.
191   struct VTable {
192     void (*copy_)(exception_wrapper const*, exception_wrapper*);
193     void (*move_)(exception_wrapper*, exception_wrapper*);
194     void (*delete_)(exception_wrapper*);
195     void (*throw_)(exception_wrapper const*);
196     std::type_info const* (*type_)(exception_wrapper const*);
197     std::exception const* (*get_exception_)(exception_wrapper const*);
198     exception_wrapper (*get_exception_ptr_)(exception_wrapper const*);
199   };
200
201   [[noreturn]] static void onNoExceptionError();
202
203   template <class Ret, class... Args>
204   static Ret noop_(Args...);
205
206   static std::type_info const* uninit_type_(exception_wrapper const*);
207
208   static constexpr VTable const uninit_{
209       &noop_<void, exception_wrapper const*, exception_wrapper*>,
210       &noop_<void, exception_wrapper*, exception_wrapper*>,
211       &noop_<void, exception_wrapper*>,
212       &noop_<void, exception_wrapper const*>,
213       &uninit_type_,
214       &noop_<std::exception const*, exception_wrapper const*>,
215       &noop_<exception_wrapper, exception_wrapper const*>};
216
217   template <class Ex>
218   using IsStdException = std::is_base_of<std::exception, _t<std::decay<Ex>>>;
219   template <bool B, class T>
220   using AddConstIf = exception_wrapper_detail::AddConstIf<B, T>;
221   template <class CatchFn>
222   using IsCatchAll =
223       std::is_same<arg_type<_t<std::decay<CatchFn>>>, AnyException>;
224
225   struct Unknown {};
226
227   // Sadly, with the gcc-4.9 platform, std::logic_error and std::runtime_error
228   // do not fit here. They also don't have noexcept copy-ctors, so the internal
229   // storage wouldn't be used anyway. For the gcc-5 platform, both logic_error
230   // and runtime_error can be safely stored internally.
231   struct Buffer {
232     using Storage =
233         _t<std::aligned_storage<2 * sizeof(void*), alignof(std::exception)>>;
234     Storage buff_;
235
236     Buffer() : buff_{} {}
237
238     template <class Ex, class DEx = _t<std::decay<Ex>>>
239     Buffer(in_place_t, Ex&& ex);
240     template <class Ex>
241     Ex& as() noexcept;
242     template <class Ex>
243     Ex const& as() const noexcept;
244   };
245
246   enum class Placement { kInSitu, kOnHeap };
247   template <class T>
248   using PlacementOf = std::integral_constant<
249       Placement,
250       sizeof(T) <= sizeof(Buffer::Storage) &&
251               alignof(T) <= alignof(Buffer::Storage) &&
252               noexcept(T(std::declval<T&&>()))
253           ? Placement::kInSitu
254           : Placement::kOnHeap>;
255
256   using InSituTag = std::integral_constant<Placement, Placement::kInSitu>;
257   using OnHeapTag = std::integral_constant<Placement, Placement::kOnHeap>;
258
259   static std::exception const* as_exception_or_null_(std::exception const& ex);
260   static std::exception const* as_exception_or_null_(AnyException);
261
262   struct ExceptionPtr {
263     std::exception_ptr ptr_;
264     std::uintptr_t exception_or_type_; // odd for type_info
265     static_assert(
266         1 < alignof(std::exception) && 1 < alignof(std::type_info),
267         "Surprise! std::exception and std::type_info don't have alignment "
268         "greater than one. as_int_ below will not work!");
269
270     static std::uintptr_t as_int_(std::exception const& e);
271     static std::uintptr_t as_int_(AnyException e);
272     bool has_exception_() const;
273     std::exception const* as_exception_() const;
274     std::type_info const* as_type_() const;
275     static void copy_(exception_wrapper const* from, exception_wrapper* to);
276     static void move_(exception_wrapper* from, exception_wrapper* to);
277     static void delete_(exception_wrapper* that);
278     [[noreturn]] static void throw_(exception_wrapper const* that);
279     static std::type_info const* type_(exception_wrapper const* that);
280     static std::exception const* get_exception_(exception_wrapper const* that);
281     static exception_wrapper get_exception_ptr_(exception_wrapper const* that);
282     static constexpr VTable const ops_{copy_,
283                                        move_,
284                                        delete_,
285                                        throw_,
286                                        type_,
287                                        get_exception_,
288                                        get_exception_ptr_};
289   };
290
291   template <class Ex>
292   struct InPlace {
293     static void copy_(exception_wrapper const* from, exception_wrapper* to);
294     static void move_(exception_wrapper* from, exception_wrapper* to);
295     static void delete_(exception_wrapper* that);
296     [[noreturn]] static void throw_(exception_wrapper const* that);
297     static std::type_info const* type_(exception_wrapper const*);
298     static std::exception const* get_exception_(exception_wrapper const* that);
299     static exception_wrapper get_exception_ptr_(exception_wrapper const* that);
300     static constexpr VTable const ops_{copy_,
301                                        move_,
302                                        delete_,
303                                        throw_,
304                                        type_,
305                                        get_exception_,
306                                        get_exception_ptr_};
307   };
308
309   struct SharedPtr {
310     struct Base {
311       std::type_info const* info_;
312       Base() = default;
313       explicit Base(std::type_info const& info) : info_(&info) {}
314       virtual ~Base() {}
315       virtual void throw_() const = 0;
316       virtual std::exception const* get_exception_() const noexcept = 0;
317       virtual exception_wrapper get_exception_ptr_() const noexcept = 0;
318     };
319     template <class Ex>
320     struct Impl final : public Base {
321       Ex ex_;
322       Impl() = default;
323       explicit Impl(Ex const& ex) : Base{typeid(ex)}, ex_(ex) {}
324       explicit Impl(Ex&& ex)
325           : Base{typeid(ex)},
326             ex_(std::move(ex)){}[[noreturn]] void throw_() const override;
327       std::exception const* get_exception_() const noexcept override;
328       exception_wrapper get_exception_ptr_() const noexcept override;
329     };
330     std::shared_ptr<Base> ptr_;
331
332     static void copy_(exception_wrapper const* from, exception_wrapper* to);
333     static void move_(exception_wrapper* from, exception_wrapper* to);
334     static void delete_(exception_wrapper* that);
335     [[noreturn]] static void throw_(exception_wrapper const* that);
336     static std::type_info const* type_(exception_wrapper const* that);
337     static std::exception const* get_exception_(exception_wrapper const* that);
338     static exception_wrapper get_exception_ptr_(exception_wrapper const* that);
339     static constexpr VTable ops_{copy_,
340                                  move_,
341                                  delete_,
342                                  throw_,
343                                  type_,
344                                  get_exception_,
345                                  get_exception_ptr_};
346   };
347
348   union {
349     Buffer buff_{};
350     ExceptionPtr eptr_;
351     SharedPtr sptr_;
352   };
353   VTable const* vptr_{&uninit_};
354
355   template <class Ex, class DEx = _t<std::decay<Ex>>>
356   exception_wrapper(Ex&& ex, OnHeapTag);
357
358   template <class Ex, class DEx = _t<std::decay<Ex>>>
359   exception_wrapper(Ex&& ex, InSituTag);
360
361   template <class T>
362   struct IsRegularExceptionType
363       : StrictConjunction<
364             std::is_copy_constructible<T>,
365             Negation<std::is_base_of<exception_wrapper, T>>,
366             Negation<std::is_abstract<T>>> {};
367
368   template <class CatchFn, bool IsConst = false>
369   struct ExceptionTypeOf;
370
371   template <bool IsConst>
372   struct HandleReduce;
373
374   template <bool IsConst>
375   struct HandleStdExceptReduce;
376
377   template <class This, class... CatchFns>
378   static void handle_(std::false_type, This& this_, CatchFns&... fns);
379
380   template <class This, class... CatchFns>
381   static void handle_(std::true_type, This& this_, CatchFns&... fns);
382
383   template <class Ex, class This, class Fn>
384   static bool with_exception_(This& this_, Fn fn_);
385
386  public:
387   //! Default-constructs an empty `exception_wrapper`
388   //! \post `type() == none()`
389   exception_wrapper() noexcept {}
390
391   //! Move-constructs an `exception_wrapper`
392   //! \post `*this` contains the value of `that` prior to the move
393   //! \post `that.type() == none()`
394   exception_wrapper(exception_wrapper&& that) noexcept;
395
396   //! Copy-constructs an `exception_wrapper`
397   //! \post `*this` contains a copy of `that`, and `that` is unmodified
398   //! \post `type() == that.type()`
399   exception_wrapper(exception_wrapper const& that);
400
401   //! Move-assigns an `exception_wrapper`
402   //! \pre `this != &that`
403   //! \post `*this` contains the value of `that` prior to the move
404   //! \post `that.type() == none()`
405   exception_wrapper& operator=(exception_wrapper&& that) noexcept;
406
407   //! Copy-assigns an `exception_wrapper`
408   //! \post `*this` contains a copy of `that`, and `that` is unmodified
409   //! \post `type() == that.type()`
410   exception_wrapper& operator=(exception_wrapper const& that);
411
412   ~exception_wrapper();
413
414   //! \pre `ptr` is empty, or it holds a reference to an exception that is not
415   //!     derived from `std::exception`.
416   //! \post `!ptr || bool(*this)`
417   //! \post `hasThrownException() == true`
418   //! \post `type() == unknown()`
419   explicit exception_wrapper(std::exception_ptr ptr) noexcept;
420
421   //! \pre `ptr` holds a reference to `ex`.
422   //! \post `hasThrownException() == true`
423   //! \post `bool(*this)`
424   //! \post `type() == typeid(ex)`
425   template <class Ex>
426   exception_wrapper(std::exception_ptr ptr, Ex& ex);
427
428   //! \pre `typeid(ex) == typeid(typename decay<Ex>::type)`
429   //! \post `bool(*this)`
430   //! \post `hasThrownException() == false`
431   //! \post `type() == typeid(ex)`
432   //! \note Exceptions of types derived from `std::exception` can be implicitly
433   //!     converted to an `exception_wrapper`.
434   template <
435       class Ex,
436       class Ex_ = _t<std::decay<Ex>>,
437       FOLLY_REQUIRES(
438           Conjunction<IsStdException<Ex_>, IsRegularExceptionType<Ex_>>())>
439   /* implicit */ exception_wrapper(Ex&& ex);
440
441   //! \pre `typeid(ex) == typeid(typename decay<Ex>::type)`
442   //! \post `bool(*this)`
443   //! \post `hasThrownException() == false`
444   //! \post `type() == typeid(ex)`
445   //! \note Exceptions of types not derived from `std::exception` can still be
446   //!     used to construct an `exception_wrapper`, but you must specify
447   //!     `folly::in_place` as the first parameter.
448   template <
449       class Ex,
450       class Ex_ = _t<std::decay<Ex>>,
451       FOLLY_REQUIRES(IsRegularExceptionType<Ex_>())>
452   exception_wrapper(in_place_t, Ex&& ex);
453
454   //! Swaps the value of `*this` with the value of `that`
455   void swap(exception_wrapper& that) noexcept;
456
457   //! \return `true` if `*this` is not holding an exception.
458   explicit operator bool() const noexcept;
459
460   //! \return `!bool(*this)`
461   bool operator!() const noexcept;
462
463   //! Make this `exception_wrapper` empty
464   //! \post `!*this`
465   void reset();
466
467   //! \return `true` if this `exception_wrapper` holds a reference to an
468   //!     exception that was thrown (i.e., if it was constructed with
469   //!     a `std::exception_ptr`, or if `to_exception_ptr()` was called on a
470   //!     (non-const) reference to `*this`).
471   bool has_exception_ptr() const noexcept;
472
473   //! \return a pointer to the `std::exception` held by `*this`, if it holds
474   //!     one; otherwise, returns `nullptr`.
475   //! \note This function does not mutate the `exception_wrapper` object.
476   //! \note This function never causes an exception to be thrown.
477   std::exception* get_exception() noexcept;
478   //! \overload
479   std::exception const* get_exception() const noexcept;
480
481   //! \return A `std::exception_ptr` that references either the exception held
482   //!     by `*this`, or a copy of same.
483   //! \note This function may need to throw an exception to complete the action.
484   //! \note The non-const overload of this function mutates `*this` to cache the
485   //!     computed `std::exception_ptr`; that is, this function may cause
486   //!     `has_exception_ptr()` to change from `false` to `true`.
487   std::exception_ptr const& to_exception_ptr() noexcept;
488   //! \overload
489   std::exception_ptr to_exception_ptr() const noexcept;
490
491   //! \return the `typeid` of an unspecified type used by
492   //!     `exception_wrapper::type()` to denote an empty `exception_wrapper`.
493   static std::type_info const& none() noexcept;
494   //! \return the `typeid` of an unspecified type used by
495   //!     `exception_wrapper::type()` to denote an `exception_wrapper` that
496   //!     holds an exception of unknown type.
497   static std::type_info const& unknown() noexcept;
498
499   //! Returns the `typeid` of the wrapped exception object. If there is no
500   //!     wrapped exception object, returns `exception_wrapper::none()`. If
501   //!     this instance wraps an exception of unknown type not derived from
502   //!     `std::exception`, returns `exception_wrapper::unknown()`.
503   std::type_info const& type() const noexcept;
504
505   //! \return If `get_exception() != nullptr`, `class_name() + ": " +
506   //!     get_exception()->what()`; otherwise, `class_name()`.
507   folly::fbstring what() const;
508
509   //! \return If `!*this`, the empty string; otherwise, if
510   //!     `type() == unknown()`, the string `"<unknown exception>"`; otherwise,
511   //!     the result of `type().name()` after demangling.
512   folly::fbstring class_name() const;
513
514   //! \tparam Ex The expression type to check for compatibility with.
515   //! \return `true` if and only if `*this` wraps an exception that would be
516   //!     caught with a `catch(Ex const&)` clause.
517   //! \note If `*this` is empty, this function returns `false`.
518   template <class Ex>
519   bool is_compatible_with() const noexcept;
520
521   //! \pre `bool(*this)`
522   //! Throws the wrapped expression.
523   [[noreturn]] void throwException() const;
524
525   //! Call `fn` with the wrapped exception (if any), if `fn` can accept it.
526   //! \par Example
527   //! \code
528   //! exception_wrapper ew{std::runtime_error("goodbye cruel world")};
529   //!
530   //! assert( ew.with_exception([](std::runtime_error& e){/*...*/}) );
531   //!
532   //! assert( !ew.with_exception([](int& e){/*...*/}) );
533   //!
534   //! assert( !exception_wrapper{}.with_exception([](int& e){/*...*/}) );
535   //! \endcode
536   //! \tparam Ex Optionally, the type of the exception that `fn` accepts.
537   //! \tparam Fn The type of a monomophic function object.
538   //! \param fn A function object to call with the wrapped exception
539   //! \return `true` if and only if `fn` was called.
540   //! \note Optionally, you may explicitly specify the type of the exception
541   //!     that `fn` expects, as in
542   //! \code
543   //! ew.with_exception<std::runtime_error>([](auto&& e) { /*...*/; });
544   //! \endcode
545   //! \note The handler may or may not be invoked with an active exception.
546   //!     **Do not try to rethrow the exception with `throw;` from within your
547   //!     handler -- that is, a throw expression with no operand.** This may
548   //!     cause your process to terminate. (It is perfectly ok to throw from
549   //!     a handler so long as you specify the exception to throw, as in
550   //!     `throw e;`.)
551   template <class Ex = void const, class Fn>
552   bool with_exception(Fn fn);
553   //! \overload
554   template <class Ex = void const, class Fn>
555   bool with_exception(Fn fn) const;
556
557   //! Handle the wrapped expression as if with a series of `catch` clauses,
558   //!     propagating the exception if no handler matches.
559   //! \par Example
560   //! \code
561   //! exception_wrapper ew{std::runtime_error("goodbye cruel world")};
562   //!
563   //! ew.handle(
564   //!   [&](std::logic_error const& e) {
565   //!      LOG(DFATAL) << "ruh roh";
566   //!      ew.throwException(); // rethrow the active exception without
567   //!                           // slicing it. Will not be caught by other
568   //!                           // handlers in this call.
569   //!   },
570   //!   [&](std::exception const& e) {
571   //!      LOG(ERROR) << ew.what();
572   //!   });
573   //! \endcode
574   //! In the above example, any exception _not_ derived from `std::exception`
575   //!     will be propagated. To specify a catch-all clause, pass a lambda that
576   //!     takes a C-style elipses, as in:
577   //! \code
578   //! ew.handle(/*...* /, [](...) { /* handle unknown exception */ } )
579   //! \endcode
580   //! \pre `!*this`
581   //! \tparam CatchFns... A pack of unary monomorphic function object types.
582   //! \param fns A pack of unary monomorphic function objects to be treated as
583   //!     an ordered list of potential exception handlers.
584   //! \note The handlers may or may not be invoked with an active exception.
585   //!     **Do not try to rethrow the exception with `throw;` from within your
586   //!     handler -- that is, a throw expression with no operand.** This may
587   //!     cause your process to terminate. (It is perfectly ok to throw from
588   //!     a handler so long as you specify the exception to throw, as in
589   //!     `throw e;`.)
590   template <class... CatchFns>
591   void handle(CatchFns... fns);
592   //! \overload
593   template <class... CatchFns>
594   void handle(CatchFns... fns) const;
595 };
596
597 template <class Ex>
598 constexpr exception_wrapper::VTable exception_wrapper::InPlace<Ex>::ops_;
599
600 /**
601  * \return An `exception_wrapper` that wraps an instance of type `Ex`
602  *     that has been constructed with arguments `std::forward<As>(as)...`.
603  */
604 template <class Ex, typename... As>
605 exception_wrapper make_exception_wrapper(As&&... as) {
606   return exception_wrapper{Ex{std::forward<As>(as)...}};
607 }
608
609 /**
610  * Inserts `ew.what()` into the ostream `sout`.
611  * \return `sout`
612  */
613 template <class Ch>
614 std::basic_ostream<Ch>& operator<<(
615     std::basic_ostream<Ch>& sout,
616     exception_wrapper const& ew) {
617   return sout << ew.what();
618 }
619
620 /**
621  * Swaps the value of `a` with the value of `b`.
622  */
623 inline void swap(exception_wrapper& a, exception_wrapper& b) noexcept {
624   a.swap(b);
625 }
626
627 // For consistency with exceptionStr() functions in ExceptionString.h
628 fbstring exceptionStr(exception_wrapper const& ew);
629
630 namespace detail {
631 template <typename F>
632 inline exception_wrapper try_and_catch_(F&& f) {
633   return (f(), exception_wrapper());
634 }
635
636 template <typename F, typename Ex, typename... Exs>
637 inline exception_wrapper try_and_catch_(F&& f) {
638   try {
639     return try_and_catch_<F, Exs...>(std::forward<F>(f));
640   } catch (Ex& ex) {
641     return exception_wrapper(std::current_exception(), ex);
642   }
643 }
644 } // detail
645
646 //! `try_and_catch` is a simple replacement for `try {} catch(){}`` that allows
647 //! you to specify which derived exceptions you would like to catch and store in
648 //! an `exception_wrapper`.
649 //!
650 //! Because we cannot build an equivalent of `std::current_exception()`, we need
651 //! to catch every derived exception that we are interested in catching.
652 //!
653 //! Exceptions should be listed in the reverse order that you would write your
654 //! catch statements (that is, `std::exception&` should be first).
655 //!
656 //! \par Example Usage:
657 //! \code
658 //! // This catches my runtime_error and if I call throwException() on ew, it
659 //! // will throw a runtime_error
660 //! auto ew = folly::try_and_catch<std::exception, std::runtime_error>([=]() {
661 //!   if (badThingHappens()) {
662 //!     throw std::runtime_error("ZOMG!");
663 //!   }
664 //! });
665 //!
666 //! // This will catch the exception and if I call throwException() on ew, it
667 //! // will throw a std::exception
668 //! auto ew = folly::try_and_catch<std::exception, std::runtime_error>([=]() {
669 //!   if (badThingHappens()) {
670 //!     throw std::exception();
671 //!   }
672 //! });
673 //!
674 //! // This will not catch the exception and it will be thrown.
675 //! auto ew = folly::try_and_catch<std::runtime_error>([=]() {
676 //!   if (badThingHappens()) {
677 //!     throw std::exception();
678 //!   }
679 //! });
680 //! \endcode
681 template <typename... Exceptions, typename F>
682 exception_wrapper try_and_catch(F&& fn) {
683   return detail::try_and_catch_<F, Exceptions...>(std::forward<F>(fn));
684 }
685 } // folly
686
687 #include <folly/ExceptionWrapper-inl.h>
688
689 #undef FOLLY_REQUIRES
690 #undef FOLLY_REQUIRES_DEF
691 #ifdef __GNUC__
692 #pragma GCC diagnostic pop
693 #endif