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  
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       * Converts input to a suitable String for exception message.
32       *
33       * @param index An index into a source collection.
34       * @param cause A cause.
35       * @return A message.
36       */
37      protected static String toMessage(final int index, final Throwable cause) {
38          // Letting index be any int
39          final String unspecified = "Null";
40          final String name = cause == null ? unspecified : cause.getClass().getSimpleName();
41          final String msg = cause == null ? unspecified : cause.getMessage();
42          return String.format("%s #%,d: %s", name, index, msg);
43      }
44  
45      /**
46       * Index.
47       */
48      private final int index;
49  
50      /**
51       * Constructs a new exception.
52       *
53       * @param index index of this exception.
54       * @param cause cause exceptions.
55       */
56      public IOIndexedException(final int index, final Throwable cause) {
57          super(toMessage(index, cause), cause);
58          this.index = index;
59      }
60  
61      /**
62       * The index of this exception.
63       *
64       * @return index of this exception.
65       */
66      public int getIndex() {
67          return index;
68      }
69  
70  }