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    *      https://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  
18  package org.apache.commons.io;
19  
20  import java.io.IOException;
21  
22  /**
23   * A IOException associated with a source index.
24   *
25   * @since 2.7
26   */
27  public class IOIndexedException extends IOException {
28  
29      private static final long serialVersionUID = 1L;
30  
31      /**
32       * Converts input to a suitable String for exception message.
33       *
34       * @param index An index into a source collection.
35       * @param cause A cause.
36       * @return A message.
37       */
38      protected static String toMessage(final int index, final Throwable cause) {
39          // Letting index be any int
40          final String unspecified = "Null";
41          final String name = cause == null ? unspecified : cause.getClass().getSimpleName();
42          final String msg = cause == null ? unspecified : cause.getMessage();
43          return String.format("%s #%,d: %s", name, index, msg);
44      }
45  
46      /**
47       * Index.
48       */
49      private final int index;
50  
51      /**
52       * Constructs a new exception.
53       *
54       * @param index index of this exception.
55       * @param cause cause exceptions.
56       */
57      public IOIndexedException(final int index, final Throwable cause) {
58          super(toMessage(index, cause), cause);
59          this.index = index;
60      }
61  
62      /**
63       * The index of this exception.
64       *
65       * @return index of this exception.
66       */
67      public int getIndex() {
68          return index;
69      }
70  
71  }