001/**
002 * Copyright (C) 2011 rwoo@gmx.de
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *         http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package com.googlecode.catchexception.internal;
017
018import java.lang.ref.WeakReference;
019
020/**
021 * Holds a caught exception {@link ThreadLocal per Thread}.
022 * 
023 * @author rwoo
024 * 
025 */
026public class ExceptionHolder {
027
028    /**
029     * The container for the most recently caught exception.
030     * <p>
031     * There is no need to use {@link WeakReference weak references} here as all
032     * the code is for testing so that we don't have to care about memory leaks.
033     */
034    private static final ThreadLocal<Exception> caughtException = new ThreadLocal<Exception>();
035
036    /**
037     * Saves the given exception in {@link #caughtException}.
038     * 
039     * @param <E>
040     *            the type of the caught exception
041     * @param caughtException
042     *            the caught exception
043     */
044    public static <E extends Exception> void set(E caughtException) {
045        ExceptionHolder.caughtException.set(caughtException);
046    }
047
048    /**
049     * @param <E>
050     *            the type of the caught exception
051     * @return Returns the caught exception. Returns null if there is no
052     *         exception caught.
053     */
054    @SuppressWarnings("unchecked")
055    public static <E extends Exception> E get() {
056        return (E) caughtException.get();
057    }
058
059}