1 /*
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 
17 package com.android.testutils;
18 
19 import java.util.function.Supplier;
20 
21 public class ExceptionUtils {
22     /**
23      * Like a Consumer, but declared to throw an exception.
24      * @param <T>
25      */
26     @FunctionalInterface
27     public interface ThrowingConsumer<T> {
accept(T 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> {
get()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 {
run()45         void run() throws Exception;
46     }
47 
48 
ignoreExceptions(ThrowingSupplier<T> func)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 }
68