1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.commons.collections4.functors;
18
19 import org.apache.commons.collections4.Closure;
20 import org.apache.commons.collections4.FunctorException;
21
22 /**
23 * {@link Closure} that catches any checked exception and re-throws it as a
24 * {@link FunctorException} runtime exception. Example usage:
25 *
26 * <pre>
27 * // Create a catch and re-throw closure via anonymous subclass
28 * CatchAndRethrowClosure<String> writer = new ThrowingClosure() {
29 * private java.io.Writer out = // some writer
30 *
31 * protected void executeAndThrow(String input) throws IOException {
32 * out.write(input); // throwing of IOException allowed
33 * }
34 * };
35 *
36 * // use catch and re-throw closure
37 * java.util.List<String> strList = // some list
38 * try {
39 * CollectionUtils.forAllDo(strList, writer);
40 * } catch (FunctorException ex) {
41 * Throwable originalError = ex.getCause();
42 * // handle error
43 * }
44 * </pre>
45 *
46 * @param <T> the type of the input to the operation.
47 * @since 4.0
48 */
49 public abstract class CatchAndRethrowClosure<T> implements Closure<T> {
50
51 /**
52 * Constructs a new instance.
53 */
54 public CatchAndRethrowClosure() {
55 // empty
56 }
57
58 /**
59 * Execute this closure on the specified input object.
60 *
61 * @param input the input to execute on
62 * @throws FunctorException (runtime) if the closure execution resulted in a
63 * checked exception.
64 */
65 @Override
66 public void execute(final T input) {
67 try {
68 executeAndThrow(input);
69 } catch (final RuntimeException ex) {
70 throw ex;
71 } catch (final Throwable t) {
72 throw new FunctorException(t);
73 }
74 }
75
76 /**
77 * Execute this closure on the specified input object.
78 *
79 * @param input the input to execute on
80 * @throws Throwable if the closure execution resulted in a checked
81 * exception.
82 */
83 protected abstract void executeAndThrow(T input) throws Throwable;
84 }