IOIndexedException.java

  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.io;

  18. import java.io.IOException;

  19. /**
  20.  * A IOException associated with a source index.
  21.  *
  22.  * @since 2.7
  23.  */
  24. public class IOIndexedException extends IOException {

  25.     private static final long serialVersionUID = 1L;
  26.     /**
  27.      * Converts input to a suitable String for exception message.
  28.      *
  29.      * @param index An index into a source collection.
  30.      * @param cause A cause.
  31.      * @return A message.
  32.      */
  33.     protected static String toMessage(final int index, final Throwable cause) {
  34.         // Letting index be any int
  35.         final String unspecified = "Null";
  36.         final String name = cause == null ? unspecified : cause.getClass().getSimpleName();
  37.         final String msg = cause == null ? unspecified : cause.getMessage();
  38.         return String.format("%s #%,d: %s", name, index, msg);
  39.     }

  40.     /**
  41.      * Index.
  42.      */
  43.     private final int index;

  44.     /**
  45.      * Constructs a new exception.
  46.      *
  47.      * @param index index of this exception.
  48.      * @param cause cause exceptions.
  49.      */
  50.     public IOIndexedException(final int index, final Throwable cause) {
  51.         super(toMessage(index, cause), cause);
  52.         this.index = index;
  53.     }

  54.     /**
  55.      * The index of this exception.
  56.      *
  57.      * @return index of this exception.
  58.      */
  59.     public int getIndex() {
  60.         return index;
  61.     }

  62. }