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 exception_wrapper&& exception() && {
212 if (!hasException()) {
213 try_detail::throwTryDoesNotContainException();
215 return std::move(e_);
218 const exception_wrapper& exception() const & {
219 if (!hasException()) {
220 try_detail::throwTryDoesNotContainException();
225 const exception_wrapper&& exception() const && {
226 if (!hasException()) {
227 try_detail::throwTryDoesNotContainException();
229 return std::move(e_);
233 * @returns a pointer to the `std::exception` held by `*this`, if one is held;
234 * otherwise, returns `nullptr`.
236 std::exception* tryGetExceptionObject() {
237 return hasException() ? e_.get_exception() : nullptr;
239 std::exception const* tryGetExceptionObject() const {
240 return hasException() ? e_.get_exception() : nullptr;
244 * @returns a pointer to the `Ex` held by `*this`, if it holds an object whose
245 * type `From` permits `std::is_convertible<From*, Ex*>`; otherwise,
249 E* tryGetExceptionObject() {
250 return hasException() ? e_.get_exception<E>() : nullptr;
253 E const* tryGetExceptionObject() const {
254 return hasException() ? e_.get_exception<E>() : nullptr;
258 * If the Try contains an exception and it is of type Ex, execute func(Ex)
260 * @param func a function that takes a single parameter of type const Ex&
262 * @returns True if the Try held an Ex and func was executed, false otherwise
264 template <class Ex, class F>
265 bool withException(F func) {
266 if (!hasException()) {
269 return e_.with_exception<Ex>(std::move(func));
271 template <class Ex, class F>
272 bool withException(F func) const {
273 if (!hasException()) {
276 return e_.with_exception<Ex>(std::move(func));
280 * If the Try contains an exception and it is of type compatible with Ex as
281 * deduced from the first parameter of func, execute func(Ex)
283 * @param func a function that takes a single parameter of type const Ex&
285 * @returns True if the Try held an Ex and func was executed, false otherwise
288 bool withException(F func) {
289 if (!hasException()) {
292 return e_.with_exception(std::move(func));
295 bool withException(F func) const {
296 if (!hasException()) {
299 return e_.with_exception(std::move(func));
302 template <bool isTry, typename R>
303 typename std::enable_if<isTry, R>::type get() {
304 return std::forward<R>(*this);
307 template <bool isTry, typename R>
308 typename std::enable_if<!isTry, R>::type get() {
309 return std::forward<R>(value());
316 exception_wrapper e_;
321 * Specialization of Try for void value type. Encapsulates either success or an
328 * The value type for the Try
330 typedef void element_type;
332 // Construct a Try holding a successful and void result
333 Try() : hasValue_(true) {}
336 * Construct a Try with an exception_wrapper
338 * @param e The exception_wrapper
340 explicit Try(exception_wrapper e) : hasValue_(false), e_(std::move(e)) {}
344 * Construct a Try with an exception_pointer
346 * @param ep The exception_pointer. Will be rethrown.
348 FOLLY_DEPRECATED("use Try(exception_wrapper)")
349 explicit Try(std::exception_ptr ep)
350 : hasValue_(false), e_(exception_wrapper::from_exception_ptr(ep)) {}
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 exception_wrapper&& exception() && {
395 if (!hasException()) {
396 try_detail::throwTryDoesNotContainException();
398 return std::move(e_);
401 const exception_wrapper& exception() const & {
402 if (!hasException()) {
403 try_detail::throwTryDoesNotContainException();
408 const exception_wrapper&& exception() const && {
409 if (!hasException()) {
410 try_detail::throwTryDoesNotContainException();
412 return std::move(e_);
416 * @returns a pointer to the `std::exception` held by `*this`, if one is held;
417 * otherwise, returns `nullptr`.
419 std::exception* tryGetExceptionObject() {
420 return hasException() ? e_.get_exception() : nullptr;
422 std::exception const* tryGetExceptionObject() const {
423 return hasException() ? e_.get_exception() : nullptr;
427 * @returns a pointer to the `Ex` held by `*this`, if it holds an object whose
428 * type `From` permits `std::is_convertible<From*, Ex*>`; otherwise,
432 E* tryGetExceptionObject() {
433 return hasException() ? e_.get_exception<E>() : nullptr;
436 E const* tryGetExceptionObject() const {
437 return hasException() ? e_.get_exception<E>() : nullptr;
441 * If the Try contains an exception and it is of type Ex, execute func(Ex)
443 * @param func a function that takes a single parameter of type const Ex&
445 * @returns True if the Try held an Ex and func was executed, false otherwise
447 template <class Ex, class F>
448 bool withException(F func) {
449 if (!hasException()) {
452 return e_.with_exception<Ex>(std::move(func));
454 template <class Ex, class F>
455 bool withException(F func) const {
456 if (!hasException()) {
459 return e_.with_exception<Ex>(std::move(func));
463 * If the Try contains an exception and it is of type compatible with Ex as
464 * deduced from the first parameter of func, execute func(Ex)
466 * @param func a function that takes a single parameter of type const Ex&
468 * @returns True if the Try held an Ex and func was executed, false otherwise
471 bool withException(F func) {
472 if (!hasException()) {
475 return e_.with_exception(std::move(func));
478 bool withException(F func) const {
479 if (!hasException()) {
482 return e_.with_exception(std::move(func));
485 template <bool, typename R>
487 return std::forward<R>(*this);
492 exception_wrapper e_;
496 * @param f a function to execute and capture the result of (value or exception)
498 * @returns Try holding the result of f
500 template <typename F>
501 typename std::enable_if<
502 !std::is_same<typename std::result_of<F()>::type, void>::value,
503 Try<typename std::result_of<F()>::type>>::type
507 * Specialization of makeTryWith for void return
509 * @param f a function to execute and capture the result of
511 * @returns Try<void> holding the result of f
513 template <typename F>
514 typename std::enable_if<
515 std::is_same<typename std::result_of<F()>::type, void>::value,
520 * Tuple<Try<Type>...> -> std::tuple<Type...>
522 * Unwraps a tuple-like type containing a sequence of Try<Type> instances to
525 template <typename Tuple>
526 auto unwrapTryTuple(Tuple&&);
530 #include <folly/Try-inl.h>