001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.commons.io;
019
020import java.io.IOException;
021
022/**
023 * A IOException associated with a source index.
024 *
025 * @since 2.7
026 */
027public class IOIndexedException extends IOException {
028
029    private static final long serialVersionUID = 1L;
030    private final int index;
031
032    /**
033     * Creates a new exception.
034     *
035     * @param index index of this exception.
036     * @param cause cause exceptions.
037     */
038    public IOIndexedException(final int index, final Throwable cause) {
039        super(toMessage(index, cause), cause);
040        this.index = index;
041    }
042
043    /**
044     * Converts input to a suitable Stirng for exception message.
045     *
046     * @param index An index into a source collection.
047     * @param cause A cause.
048     * @return A message.
049     */
050    protected static String toMessage(final int index, final Throwable cause) {
051        // Letting index be any int
052        final String unspecified = "Null";
053        final String name = cause == null ? unspecified : cause.getClass().getSimpleName();
054        final String msg = cause == null ? unspecified : cause.getMessage();
055        return String.format("%s #%,d: %s", name, index, msg);
056    }
057
058    /**
059     * The index of this exception.
060     *
061     * @return index of this exception.
062     */
063    public int getIndex() {
064        return index;
065    }
066
067}