blob: d3bda98cb085436d7afa92d4f37a25e1b35f59ba [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
Chalard Jeane06c5c82020-06-26 00:16:27 +090021/**
22 * A class grouping some utilities to deal with exceptions.
23 */
Chalard Jean48c6c7d2020-06-25 23:39:15 +090024public class ExceptionUtils {
25 /**
26 * Like a Consumer, but declared to throw an exception.
27 * @param <T>
28 */
29 @FunctionalInterface
30 public interface ThrowingConsumer<T> {
Chalard Jeane06c5c82020-06-26 00:16:27 +090031 /** @see java.util.function.Consumer */
Chalard Jean48c6c7d2020-06-25 23:39:15 +090032 void accept(T t) throws Exception;
33 }
34
35 /**
36 * Like a Supplier, but declared to throw an exception.
37 * @param <T>
38 */
39 @FunctionalInterface
40 public interface ThrowingSupplier<T> {
Chalard Jeane06c5c82020-06-26 00:16:27 +090041 /** @see java.util.function.Supplier */
Chalard Jean48c6c7d2020-06-25 23:39:15 +090042 T get() throws Exception;
43 }
44
45 /**
46 * Like a Runnable, but declared to throw an exception.
47 */
48 @FunctionalInterface
49 public interface ThrowingRunnable {
Chalard Jeane06c5c82020-06-26 00:16:27 +090050 /** @see java.lang.Runnable */
Chalard Jean48c6c7d2020-06-25 23:39:15 +090051 void run() throws Exception;
52 }
53
Chalard Jeane06c5c82020-06-26 00:16:27 +090054 /**
55 * Convert a supplier that throws into one that doesn't.
56 *
57 * The returned supplier returns null in cases where the source throws.
58 */
Chalard Jean48c6c7d2020-06-25 23:39:15 +090059 public static <T> Supplier<T> ignoreExceptions(ThrowingSupplier<T> func) {
60 return () -> {
61 try {
62 return func.get();
63 } catch (Exception e) {
64 return null;
65 }
66 };
67 }
68
Chalard Jeane06c5c82020-06-26 00:16:27 +090069 /**
70 * Convert a runnable that throws into one that doesn't.
71 *
72 * All exceptions are ignored by the returned Runnable.
73 */
Chalard Jean48c6c7d2020-06-25 23:39:15 +090074 public static Runnable ignoreExceptions(ThrowingRunnable r) {
75 return () -> {
76 try {
77 r.run();
78 } catch (Exception e) {
79 }
80 };
81 }
82}