View Javadoc
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&lt;String&gt; 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&lt;String&gt; 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   * @since 4.0
47   */
48  public abstract class CatchAndRethrowClosure<E> implements Closure<E> {
49  
50      /**
51       * Execute this closure on the specified input object.
52       *
53       * @param input the input to execute on
54       * @throws FunctorException (runtime) if the closure execution resulted in a
55       *             checked exception.
56       */
57      @Override
58      public void execute(final E input) {
59          try {
60              executeAndThrow(input);
61          } catch (final RuntimeException ex) {
62              throw ex;
63          } catch (final Throwable t) {
64              throw new FunctorException(t);
65          }
66      }
67  
68      /**
69       * Execute this closure on the specified input object.
70       *
71       * @param input the input to execute on
72       * @throws Throwable if the closure execution resulted in a checked
73       *             exception.
74       */
75      protected abstract void executeAndThrow(E input) throws Throwable;
76  }