1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 package org.apache.commons.dbcp;
19
20 import java.io.PrintStream;
21 import java.io.PrintWriter;
22 import java.lang.reflect.Method;
23 import java.sql.DriverManager;
24 import java.sql.SQLException;
25
26 /**
27 * A SQLException subclass containing another Throwable
28 *
29 * @author Dirk Verbeeck
30 * @version $Revision: 479137 $ $Date: 2006-11-25 08:51:48 -0700 (Sat, 25 Nov 2006) $
31 */
32 public class SQLNestedException extends SQLException {
33
34 /* Throwable.getCause detection as found in commons-lang */
35 private static final Method THROWABLE_CAUSE_METHOD;
36 static {
37 Method getCauseMethod;
38 try {
39 getCauseMethod = Throwable.class.getMethod("getCause", (Class[]) null);
40 } catch (Exception e) {
41 getCauseMethod = null;
42 }
43 THROWABLE_CAUSE_METHOD = getCauseMethod;
44 }
45
46 private static boolean hasThrowableCauseMethod() {
47 return THROWABLE_CAUSE_METHOD != null;
48 }
49
50 /**
51 * Holds the reference to the exception or error that caused
52 * this exception to be thrown.
53 */
54 private Throwable cause = null;
55
56 /**
57 * Constructs a new <code>SQLNestedException</code> with specified
58 * detail message and nested <code>Throwable</code>.
59 *
60 * @param msg the error message
61 * @param cause the exception or error that caused this exception to be
62 * thrown
63 */
64 public SQLNestedException(String msg, Throwable cause) {
65 super(msg);
66 this.cause = cause;
67 if ((cause != null) && (DriverManager.getLogWriter() != null)) {
68 DriverManager.getLogWriter().print("Caused by: ");
69 cause.printStackTrace(DriverManager.getLogWriter());
70 }
71 }
72
73 public Throwable getCause() {
74 return this.cause;
75 }
76
77 public void printStackTrace(PrintStream s) {
78 super.printStackTrace(s);
79 if ((cause != null) && !hasThrowableCauseMethod()) {
80 s.print("Caused by: ");
81 this.cause.printStackTrace(s);
82 }
83 }
84
85 public void printStackTrace(PrintWriter s) {
86 super.printStackTrace(s);
87 if ((cause != null) && !hasThrowableCauseMethod()) {
88 s.print("Caused by: ");
89 this.cause.printStackTrace(s);
90 }
91 }
92 }