1 29 package net.sourceforge.groboutils.util.throwable.v1; 30 31 import java.io.PrintStream ; 32 import java.io.PrintWriter ; 33 import java.io.Serializable ; 34 35 56 public class ChainableExceptionHelper implements Serializable 57 { 58 private Throwable source; 59 60 66 private Throwable cause; 67 68 72 private boolean causeSet = false; 73 74 75 79 public ChainableExceptionHelper( Throwable source ) 80 { 81 if (source == null) 82 { 83 throw new IllegalArgumentException ("no null arguments"); 84 } 85 this.source = source; 86 } 87 88 89 public ChainableExceptionHelper( Throwable source, Throwable cause ) 90 { 91 this( source ); 92 initCause( cause ); 93 } 94 95 96 119 public Throwable getCause() 120 { 121 Throwable t = null; 122 if (this.causeSet) 123 { 124 t = this.cause; 126 } 127 return t; 128 } 129 130 131 156 public synchronized Throwable initCause( Throwable cause ) 157 { 158 if (this.causeSet) 159 { 160 throw new IllegalStateException ("Already set cause"); 161 } 162 if (cause == this.source) 163 { 164 throw new IllegalArgumentException ( 165 "exception cannot cause itself." ); 166 } 167 168 this.causeSet = true; 169 this.cause = cause; 170 return this.source; 171 } 172 173 174 180 public void printStackTrace( PrintStream ps ) 181 { 182 this.source.printStackTrace( ps ); 183 if (shouldDisplayCause()) 184 { 185 ps.println( getUnderlyingExceptionSeparator() ); 186 Throwable t = getCause(); 187 if (t == null) 188 { 189 ps.println( getUnknownExceptionString() ); 190 } 191 else 192 { 193 t.printStackTrace( ps ); 194 } 195 } 196 } 197 198 199 200 206 public void printStackTrace( PrintWriter pw ) 207 { 208 this.source.printStackTrace( pw ); 209 if (shouldDisplayCause()) 210 { 211 pw.println( getUnderlyingExceptionSeparator() ); 212 Throwable t = getCause(); 213 if (t == null) 214 { 215 pw.println( getUnknownExceptionString() ); 216 } 217 else 218 { 219 t.printStackTrace( pw ); 220 } 221 } 222 } 223 224 225 226 protected String getUnderlyingExceptionSeparator() 227 { 228 return "-------- Underlying exception --------"; 229 } 230 231 232 protected String getUnknownExceptionString() 233 { 234 return "Unknown or non-existent exception"; 235 } 236 237 238 protected boolean shouldDisplayCause() 239 { 240 if (!this.causeSet) 243 { 244 return false; 245 } 246 247 return true; 249 } 250 } 251 252 | Popular Tags |