View Javadoc

1   /*
2    * Copyright 2004 Ronald Blaschke.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.rblasch.convert;
17  
18  import java.io.PrintStream;
19  import java.io.PrintWriter;
20  
21  /***
22   * @author Ronald Blaschke
23   */
24  public abstract class AbstractRuntimeException extends RuntimeException {
25      private Throwable cause = this;
26  
27      public AbstractRuntimeException() {
28      }
29  
30      public AbstractRuntimeException(final String message) {
31          super(message);
32      }
33  
34      public AbstractRuntimeException(final String message, final Throwable cause) {
35          super(message);
36          this.cause = cause;
37      }
38  
39      public AbstractRuntimeException(final Throwable cause) {
40          super(cause == null ? null : cause.toString());
41          this.cause = cause;
42      }
43  
44      public Throwable getCause() {
45          return (cause == this ? null : cause);
46      }
47  
48      public synchronized Throwable initCause(final Throwable cause) {
49          if (this.cause != this)
50              throw new IllegalStateException("Can't overwrite cause");
51          if (cause == this)
52              throw new IllegalArgumentException("Self-causation not permitted");
53          this.cause = cause;
54          return this;
55      }
56  
57      public void printStackTrace() {
58          synchronized (System.err) {
59              printStackTrace(System.err);
60          }
61      }
62  
63      public void printStackTrace(final PrintStream s) {
64          synchronized (s) {
65              super.printStackTrace(s);
66  
67              final Throwable ourCause = getCause();
68              if (ourCause != null) {
69                  s.println("Caused by: " + ourCause);
70                  ourCause.printStackTrace(s);
71              }
72          }
73      }
74  
75      public void printStackTrace(final PrintWriter s) {
76          synchronized (s) {
77              super.printStackTrace(s);
78  
79              final Throwable ourCause = getCause();
80              if (ourCause != null) {
81                  s.println("Caused by: " + ourCause);
82                  ourCause.printStackTrace(s);
83              }
84          }
85      }
86  }