Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
 // ========================================================================
 // Copyright 1999-2005 Mort Bay Consulting Pty. Ltd.
 // ------------------------------------------------------------------------
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
 // You may obtain a copy of the License at
 // http://www.apache.org/licenses/LICENSE-2.0
 // Unless required by applicable law or agreed to in writing, software
 // distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================
package com.googlecode.junittoolbox.util;
Allows multiple exceptions to be thrown as a single exception -- adapted from Jetty.
public class MultiException extends RuntimeException {
    private static final long serialVersionUID = 1L;
    private static final String EXCEPTION_SEPARATOR = "\n\t______________________________________________________________________\n";
    private final List<Throwablenested = new ArrayList<Throwable>();
    public MultiException() {
        super("Multiple exceptions");
    }
    public void add(Throwable throwable) {
        if (throwable != null) {
            if (throwable instanceof MultiException) {
                MultiException me = (MultiExceptionthrowable;
                .addAll(me.nested);
            } else {
                .add(throwable);
            }
        }
    }
    public boolean isEmpty() {
        return .isEmpty();
    }

    
If this multi exception is empty then no action is taken, if it contains a single Throwable that is thrown, otherwise this MultiException is thrown.
    public void throwIfNotEmpty() {
        if (.isEmpty()) {
            // Do nothing
        } else if (.size() == 1) {
            Throwable t = .get(0);
            TigerThrower.sneakyThrow(t);
        } else {
            throw this;
        }
    }
    @Override
    public String getMessage() {
        if (.isEmpty()) {
            return "<no nested exceptions>";
        } else {
            StringBuilder sb = new StringBuilder();
            int n = .size();
            sb.append(n).append(n == 1 ? " nested exception:" : " nested exceptions:");
            for (Throwable t : ) {
                sb.append().append("\n\t");
                StringWriter sw = new StringWriter();
                t.printStackTrace(new PrintWriter(sw));
                sb.append(sw.toString().replace("\n""\n\t").trim());
            }
            sb.append();
            return sb.toString();
        }
    }
New to GrepCode? Check out our FAQ X