2 * Copyright 2017 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <folly/ExceptionWrapper.h>
20 #include <folly/Likely.h>
21 #include <folly/Memory.h>
22 #include <folly/Portability.h>
23 #include <folly/Unit.h>
24 #include <folly/Utility.h>
27 #include <type_traits>
32 class TryException : public std::logic_error {
34 using std::logic_error::logic_error;
37 class UsingUninitializedTry : public TryException {
39 UsingUninitializedTry() : TryException("Using uninitialized try") {}
42 namespace try_detail {
43 [[noreturn]] void throwTryDoesNotContainException();
44 [[noreturn]] void throwUsingUninitializedTry();
45 } // namespace try_detail
48 * Try<T> is a wrapper that contains either an instance of T, an exception, or
49 * nothing. Exceptions are stored as exception_wrappers so that the user can
50 * minimize rethrows if so desired.
52 * To represent success or a captured exception, use Try<Unit>.
56 static_assert(!std::is_reference<T>::value,
57 "Try may not be used with reference types");
67 * The value type for the Try
69 typedef T element_type;
72 * Construct an empty Try
74 Try() : contains_(Contains::NOTHING) {}
77 * Construct a Try with a value by copy
79 * @param v The value to copy in
81 explicit Try(const T& v) : contains_(Contains::VALUE), value_(v) {}
84 * Construct a Try with a value by move
86 * @param v The value to move in
88 explicit Try(T&& v) : contains_(Contains::VALUE), value_(std::move(v)) {}
90 template <typename... Args>
91 explicit Try(in_place_t, Args&&... args) noexcept(
92 noexcept(::new (nullptr) T(std::declval<Args&&>()...)))
93 : contains_(Contains::VALUE), value_(std::forward<Args>(args)...) {}
95 /// Implicit conversion from Try<void> to Try<Unit>
96 template <class T2 = T>
98 Try(typename std::enable_if<std::is_same<Unit, T2>::value,
99 Try<void> const&>::type t);
102 * Construct a Try with an exception_wrapper
104 * @param e The exception_wrapper
106 explicit Try(exception_wrapper e)
107 : contains_(Contains::EXCEPTION), e_(std::move(e)) {}
111 * Construct a Try with an exception_pointer
113 * @param ep The exception_pointer. Will be rethrown.
115 FOLLY_DEPRECATED("use Try(exception_wrapper)")
116 explicit Try(std::exception_ptr ep)
117 : contains_(Contains::EXCEPTION),
118 e_(exception_wrapper::from_exception_ptr(ep)) {}
121 Try(Try<T>&& t) noexcept;
123 Try& operator=(Try<T>&& t) noexcept;
128 Try& operator=(const Try& t);
133 * Get a mutable reference to the contained value. If the Try contains an
134 * exception it will be rethrown.
136 * @returns mutable reference to the contained value
140 * Get a rvalue reference to the contained value. If the Try contains an
141 * exception it will be rethrown.
143 * @returns rvalue reference to the contained value
147 * Get a const reference to the contained value. If the Try contains an
148 * exception it will be rethrown.
150 * @returns const reference to the contained value
152 const T& value() const&;
155 * If the Try contains an exception, rethrow it. Otherwise do nothing.
157 void throwIfFailed() const;
160 * Const dereference operator. If the Try contains an exception it will be
163 * @returns const reference to the contained value
165 const T& operator*() const { return value(); }
167 * Dereference operator. If the Try contains an exception it will be rethrown.
169 * @returns mutable reference to the contained value
171 T& operator*() { return value(); }
174 * Const arrow operator. If the Try contains an exception it will be
177 * @returns const reference to the contained value
179 const T* operator->() const { return &value(); }
181 * Arrow operator. If the Try contains an exception it will be rethrown.
183 * @returns mutable reference to the contained value
185 T* operator->() { return &value(); }
188 * @returns True if the Try contains a value, false otherwise
190 bool hasValue() const { return contains_ == Contains::VALUE; }
192 * @returns True if the Try contains an exception, false otherwise
194 bool hasException() const { return contains_ == Contains::EXCEPTION; }
197 * @returns True if the Try contains an exception of type Ex, false otherwise
200 bool hasException() const {
201 return hasException() && e_.is_compatible_with<Ex>();
204 exception_wrapper& exception() {
205 if (!hasException()) {
206 try_detail::throwTryDoesNotContainException();
211 const exception_wrapper& exception() const {
212 if (!hasException()) {
213 try_detail::throwTryDoesNotContainException();
219 * @returns a pointer to the `std::exception` held by `*this`, if one is held;
220 * otherwise, returns `nullptr`.
222 std::exception* tryGetExceptionObject() {
223 return hasException() ? e_.get_exception() : nullptr;
225 std::exception const* tryGetExceptionObject() const {
226 return hasException() ? e_.get_exception() : nullptr;
230 * @returns a pointer to the `Ex` held by `*this`, if it holds an object whose
231 * type `From` permits `std::is_convertible<From*, Ex*>`; otherwise,
235 E* tryGetExceptionObject() {
236 return hasException() ? e_.get_exception<E>() : nullptr;
239 E const* tryGetExceptionObject() const {
240 return hasException() ? e_.get_exception<E>() : nullptr;
244 * If the Try contains an exception and it is of type Ex, execute func(Ex)
246 * @param func a function that takes a single parameter of type const Ex&
248 * @returns True if the Try held an Ex and func was executed, false otherwise
250 template <class Ex, class F>
251 bool withException(F func) {
252 if (!hasException()) {
255 return e_.with_exception<Ex>(std::move(func));
257 template <class Ex, class F>
258 bool withException(F func) const {
259 if (!hasException()) {
262 return e_.with_exception<Ex>(std::move(func));
266 * If the Try contains an exception and it is of type compatible with Ex as
267 * deduced from the first parameter of func, execute func(Ex)
269 * @param func a function that takes a single parameter of type const Ex&
271 * @returns True if the Try held an Ex and func was executed, false otherwise
274 bool withException(F func) {
275 if (!hasException()) {
278 return e_.with_exception(std::move(func));
281 bool withException(F func) const {
282 if (!hasException()) {
285 return e_.with_exception(std::move(func));
288 template <bool isTry, typename R>
289 typename std::enable_if<isTry, R>::type get() {
290 return std::forward<R>(*this);
293 template <bool isTry, typename R>
294 typename std::enable_if<!isTry, R>::type get() {
295 return std::forward<R>(value());
302 exception_wrapper e_;
307 * Specialization of Try for void value type. Encapsulates either success or an
314 * The value type for the Try
316 typedef void element_type;
318 // Construct a Try holding a successful and void result
319 Try() : hasValue_(true) {}
322 * Construct a Try with an exception_wrapper
324 * @param e The exception_wrapper
326 explicit Try(exception_wrapper e) : hasValue_(false), e_(std::move(e)) {}
330 * Construct a Try with an exception_pointer
332 * @param ep The exception_pointer. Will be rethrown.
334 FOLLY_DEPRECATED("use Try(exception_wrapper)")
335 explicit Try(std::exception_ptr ep)
336 : hasValue_(false), e_(exception_wrapper::from_exception_ptr(ep)) {}
339 Try& operator=(const Try<void>& t) {
340 hasValue_ = t.hasValue_;
345 Try(const Try<void>& t) {
349 // If the Try contains an exception, throws it
350 void value() const { throwIfFailed(); }
351 // Dereference operator. If the Try contains an exception, throws it
352 void operator*() const { return value(); }
354 // If the Try contains an exception, throws it
355 inline void throwIfFailed() const;
357 // @returns False if the Try contains an exception, true otherwise
358 bool hasValue() const { return hasValue_; }
359 // @returns True if the Try contains an exception, false otherwise
360 bool hasException() const { return !hasValue_; }
362 // @returns True if the Try contains an exception of type Ex, false otherwise
364 bool hasException() const {
365 return hasException() && e_.is_compatible_with<Ex>();
369 * @throws TryException if the Try doesn't contain an exception
371 * @returns mutable reference to the exception contained by this Try
373 exception_wrapper& exception() {
374 if (!hasException()) {
375 try_detail::throwTryDoesNotContainException();
380 const exception_wrapper& exception() const {
381 if (!hasException()) {
382 try_detail::throwTryDoesNotContainException();
388 * @returns a pointer to the `std::exception` held by `*this`, if one is held;
389 * otherwise, returns `nullptr`.
391 std::exception* tryGetExceptionObject() {
392 return hasException() ? e_.get_exception() : nullptr;
394 std::exception const* tryGetExceptionObject() const {
395 return hasException() ? e_.get_exception() : nullptr;
399 * @returns a pointer to the `Ex` held by `*this`, if it holds an object whose
400 * type `From` permits `std::is_convertible<From*, Ex*>`; otherwise,
404 E* tryGetExceptionObject() {
405 return hasException() ? e_.get_exception<E>() : nullptr;
408 E const* tryGetExceptionObject() const {
409 return hasException() ? e_.get_exception<E>() : nullptr;
413 * If the Try contains an exception and it is of type Ex, execute func(Ex)
415 * @param func a function that takes a single parameter of type const Ex&
417 * @returns True if the Try held an Ex and func was executed, false otherwise
419 template <class Ex, class F>
420 bool withException(F func) {
421 if (!hasException()) {
424 return e_.with_exception<Ex>(std::move(func));
426 template <class Ex, class F>
427 bool withException(F func) const {
428 if (!hasException()) {
431 return e_.with_exception<Ex>(std::move(func));
435 * If the Try contains an exception and it is of type compatible with Ex as
436 * deduced from the first parameter of func, execute func(Ex)
438 * @param func a function that takes a single parameter of type const Ex&
440 * @returns True if the Try held an Ex and func was executed, false otherwise
443 bool withException(F func) {
444 if (!hasException()) {
447 return e_.with_exception(std::move(func));
450 bool withException(F func) const {
451 if (!hasException()) {
454 return e_.with_exception(std::move(func));
457 template <bool, typename R>
459 return std::forward<R>(*this);
464 exception_wrapper e_;
468 * @param f a function to execute and capture the result of (value or exception)
470 * @returns Try holding the result of f
472 template <typename F>
473 typename std::enable_if<
474 !std::is_same<typename std::result_of<F()>::type, void>::value,
475 Try<typename std::result_of<F()>::type>>::type
479 * Specialization of makeTryWith for void return
481 * @param f a function to execute and capture the result of
483 * @returns Try<void> holding the result of f
485 template <typename F>
486 typename std::enable_if<
487 std::is_same<typename std::result_of<F()>::type, void>::value,
491 template <typename... Ts>
492 std::tuple<Ts...> unwrapTryTuple(std::tuple<folly::Try<Ts>...>&& ts);
496 #include <folly/Try-inl.h>