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) {
119 std::rethrow_exception(ep);
120 } catch (std::exception& e) {
121 e_ = exception_wrapper(std::current_exception(), e);
123 e_ = exception_wrapper(std::current_exception());
128 Try(Try<T>&& t) noexcept;
130 Try& operator=(Try<T>&& t) noexcept;
135 Try& operator=(const Try& t);
140 * Get a mutable reference to the contained value. If the Try contains an
141 * exception it will be rethrown.
143 * @returns mutable reference to the contained value
147 * Get a rvalue reference to the contained value. If the Try contains an
148 * exception it will be rethrown.
150 * @returns rvalue reference to the contained value
154 * Get a const reference to the contained value. If the Try contains an
155 * exception it will be rethrown.
157 * @returns const reference to the contained value
159 const T& value() const&;
162 * If the Try contains an exception, rethrow it. Otherwise do nothing.
164 void throwIfFailed() const;
167 * Const dereference operator. If the Try contains an exception it will be
170 * @returns const reference to the contained value
172 const T& operator*() const { return value(); }
174 * Dereference operator. If the Try contains an exception it will be rethrown.
176 * @returns mutable reference to the contained value
178 T& operator*() { return value(); }
181 * Const arrow operator. If the Try contains an exception it will be
184 * @returns const reference to the contained value
186 const T* operator->() const { return &value(); }
188 * Arrow operator. If the Try contains an exception it will be rethrown.
190 * @returns mutable reference to the contained value
192 T* operator->() { return &value(); }
195 * @returns True if the Try contains a value, false otherwise
197 bool hasValue() const { return contains_ == Contains::VALUE; }
199 * @returns True if the Try contains an exception, false otherwise
201 bool hasException() const { return contains_ == Contains::EXCEPTION; }
204 * @returns True if the Try contains an exception of type Ex, false otherwise
207 bool hasException() const {
208 return hasException() && e_.is_compatible_with<Ex>();
211 exception_wrapper& exception() {
212 if (!hasException()) {
213 try_detail::throwTryDoesNotContainException();
218 const exception_wrapper& exception() const {
219 if (!hasException()) {
220 try_detail::throwTryDoesNotContainException();
226 * @returns a pointer to the `std::exception` held by `*this`, if one is held;
227 * otherwise, returns `nullptr`.
229 std::exception* tryGetExceptionObject() {
230 return hasException() ? e_.get_exception() : nullptr;
232 std::exception const* tryGetExceptionObject() const {
233 return hasException() ? e_.get_exception() : nullptr;
237 * @returns a pointer to the `Ex` held by `*this`, if it holds an object whose
238 * type `From` permits `std::is_convertible<From*, Ex*>`; otherwise,
242 E* tryGetExceptionObject() {
243 return hasException() ? e_.get_exception<E>() : nullptr;
246 E const* tryGetExceptionObject() const {
247 return hasException() ? e_.get_exception<E>() : nullptr;
251 * If the Try contains an exception and it is of type Ex, execute func(Ex)
253 * @param func a function that takes a single parameter of type const Ex&
255 * @returns True if the Try held an Ex and func was executed, false otherwise
257 template <class Ex, class F>
258 bool withException(F func) {
259 if (!hasException()) {
262 return e_.with_exception<Ex>(std::move(func));
264 template <class Ex, class F>
265 bool withException(F func) const {
266 if (!hasException()) {
269 return e_.with_exception<Ex>(std::move(func));
273 * If the Try contains an exception and it is of type compatible with Ex as
274 * deduced from the first parameter of func, execute func(Ex)
276 * @param func a function that takes a single parameter of type const Ex&
278 * @returns True if the Try held an Ex and func was executed, false otherwise
281 bool withException(F func) {
282 if (!hasException()) {
285 return e_.with_exception(std::move(func));
288 bool withException(F func) const {
289 if (!hasException()) {
292 return e_.with_exception(std::move(func));
295 template <bool isTry, typename R>
296 typename std::enable_if<isTry, R>::type get() {
297 return std::forward<R>(*this);
300 template <bool isTry, typename R>
301 typename std::enable_if<!isTry, R>::type get() {
302 return std::forward<R>(value());
309 exception_wrapper e_;
314 * Specialization of Try for void value type. Encapsulates either success or an
321 * The value type for the Try
323 typedef void element_type;
325 // Construct a Try holding a successful and void result
326 Try() : hasValue_(true) {}
329 * Construct a Try with an exception_wrapper
331 * @param e The exception_wrapper
333 explicit Try(exception_wrapper e) : hasValue_(false), e_(std::move(e)) {}
337 * Construct a Try with an exception_pointer
339 * @param ep The exception_pointer. Will be rethrown.
341 FOLLY_DEPRECATED("use Try(exception_wrapper)")
342 explicit Try(std::exception_ptr ep) : hasValue_(false) {
344 std::rethrow_exception(ep);
345 } catch (const std::exception& e) {
346 e_ = exception_wrapper(std::current_exception(), e);
348 e_ = exception_wrapper(std::current_exception());
353 Try& operator=(const Try<void>& t) {
354 hasValue_ = t.hasValue_;
359 Try(const Try<void>& t) {
363 // If the Try contains an exception, throws it
364 void value() const { throwIfFailed(); }
365 // Dereference operator. If the Try contains an exception, throws it
366 void operator*() const { return value(); }
368 // If the Try contains an exception, throws it
369 inline void throwIfFailed() const;
371 // @returns False if the Try contains an exception, true otherwise
372 bool hasValue() const { return hasValue_; }
373 // @returns True if the Try contains an exception, false otherwise
374 bool hasException() const { return !hasValue_; }
376 // @returns True if the Try contains an exception of type Ex, false otherwise
378 bool hasException() const {
379 return hasException() && e_.is_compatible_with<Ex>();
383 * @throws TryException if the Try doesn't contain an exception
385 * @returns mutable reference to the exception contained by this Try
387 exception_wrapper& exception() {
388 if (!hasException()) {
389 try_detail::throwTryDoesNotContainException();
394 const exception_wrapper& exception() const {
395 if (!hasException()) {
396 try_detail::throwTryDoesNotContainException();
402 * @returns a pointer to the `std::exception` held by `*this`, if one is held;
403 * otherwise, returns `nullptr`.
405 std::exception* tryGetExceptionObject() {
406 return hasException() ? e_.get_exception() : nullptr;
408 std::exception const* tryGetExceptionObject() const {
409 return hasException() ? e_.get_exception() : nullptr;
413 * @returns a pointer to the `Ex` held by `*this`, if it holds an object whose
414 * type `From` permits `std::is_convertible<From*, Ex*>`; otherwise,
418 E* tryGetExceptionObject() {
419 return hasException() ? e_.get_exception<E>() : nullptr;
422 E const* tryGetExceptionObject() const {
423 return hasException() ? e_.get_exception<E>() : nullptr;
427 * If the Try contains an exception and it is of type Ex, execute func(Ex)
429 * @param func a function that takes a single parameter of type const Ex&
431 * @returns True if the Try held an Ex and func was executed, false otherwise
433 template <class Ex, class F>
434 bool withException(F func) {
435 if (!hasException()) {
438 return e_.with_exception<Ex>(std::move(func));
440 template <class Ex, class F>
441 bool withException(F func) const {
442 if (!hasException()) {
445 return e_.with_exception<Ex>(std::move(func));
449 * If the Try contains an exception and it is of type compatible with Ex as
450 * deduced from the first parameter of func, execute func(Ex)
452 * @param func a function that takes a single parameter of type const Ex&
454 * @returns True if the Try held an Ex and func was executed, false otherwise
457 bool withException(F func) {
458 if (!hasException()) {
461 return e_.with_exception(std::move(func));
464 bool withException(F func) const {
465 if (!hasException()) {
468 return e_.with_exception(std::move(func));
471 template <bool, typename R>
473 return std::forward<R>(*this);
478 exception_wrapper e_;
482 * Extracts value from try and returns it. Throws if try contained an exception.
484 * @param t Try to extract value from
486 * @returns value contained in t
488 template <typename T>
489 T moveFromTry(Try<T>& t);
492 * Throws if try contained an exception.
494 * @param t Try to move from
496 void moveFromTry(Try<void>& t);
499 * @param f a function to execute and capture the result of (value or exception)
501 * @returns Try holding the result of f
503 template <typename F>
504 typename std::enable_if<
505 !std::is_same<typename std::result_of<F()>::type, void>::value,
506 Try<typename std::result_of<F()>::type>>::type
510 * Specialization of makeTryWith for void return
512 * @param f a function to execute and capture the result of
514 * @returns Try<void> holding the result of f
516 template <typename F>
517 typename std::enable_if<
518 std::is_same<typename std::result_of<F()>::type, void>::value,
522 template <typename... Ts>
523 std::tuple<Ts...> unwrapTryTuple(std::tuple<folly::Try<Ts>...>&& ts);
527 #include <folly/Try-inl.h>