blob: e7dbed5dd14f0bce49fedbb8ba07fe21b584147f [file] [log] [blame]
Chalard Jean48c6c7d2020-06-25 23:39:15 +09001/*
2 * Copyright (C) 2019 The Android Open Source Project
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
17package com.android.testutils;
18
19import java.util.function.Supplier;
20
21public class ExceptionUtils {
22 /**
23 * Like a Consumer, but declared to throw an exception.
24 * @param <T>
25 */
26 @FunctionalInterface
27 public interface ThrowingConsumer<T> {
28 void accept(T t) throws Exception;
29 }
30
31 /**
32 * Like a Supplier, but declared to throw an exception.
33 * @param <T>
34 */
35 @FunctionalInterface
36 public interface ThrowingSupplier<T> {
37 T get() throws Exception;
38 }
39
40 /**
41 * Like a Runnable, but declared to throw an exception.
42 */
43 @FunctionalInterface
44 public interface ThrowingRunnable {
45 void run() throws Exception;
46 }
47
48
49 public static <T> Supplier<T> ignoreExceptions(ThrowingSupplier<T> func) {
50 return () -> {
51 try {
52 return func.get();
53 } catch (Exception e) {
54 return null;
55 }
56 };
57 }
58
59 public static Runnable ignoreExceptions(ThrowingRunnable r) {
60 return () -> {
61 try {
62 r.run();
63 } catch (Exception e) {
64 }
65 };
66 }
67}