001 /** 002 * 003 * Copyright 2004 Protique Ltd 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * 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 **/ 018 package org.activemq.util; 019 020 import org.activemq.util.JMSExceptionHelper; 021 022 import javax.jms.JMSException; 023 024 /** 025 * A helper class for ensuring that a number of tasks occur, whether they 026 * throw exceptions or not and saving the first exception so that we can 027 * throw it properly. 028 * This class is particularly useful for shutting things down, where we 029 * want to try close all resources, whether they fail or not. 030 * 031 * @version $Revision: 1.1.1.1 $ 032 */ 033 public class ExceptionTemplate { 034 private Throwable firstException; 035 036 public ExceptionTemplate() { 037 } 038 039 public void run(Callback task) { 040 try { 041 task.execute(); 042 } 043 catch (Throwable t) { 044 if (firstException == null) { 045 firstException = t; 046 } 047 } 048 } 049 050 /** 051 * Returns the first exception thrown during the execution of this 052 * template or returns null if there has been no exception thrown yet. 053 * 054 * @return the first caught exception or null if none has occured yet 055 */ 056 public Throwable getFirstException() { 057 return firstException; 058 } 059 060 /** 061 * Throws the first exception caught during the execution of this template 062 * as a JMS exception or do nothing if we have not caught and exception 063 * 064 * @throws JMSException 065 */ 066 public void throwJMSException() throws JMSException { 067 if (firstException != null) { 068 if (firstException instanceof JMSException) { 069 throw (JMSException) firstException; 070 } 071 else if (firstException instanceof Exception) { 072 throw JMSExceptionHelper.newJMSException(firstException.getMessage(), (Exception) firstException); 073 } 074 else { 075 // lets wrap the Throwable in an Exception 076 throw JMSExceptionHelper.newJMSException(firstException.getMessage(), new Exception(firstException)); 077 } 078 } 079 } 080 }