1. /*
  2. * Copyright 1999-2004 The Apache Software Foundation.
  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.apache.commons.dbcp;
  17. import java.io.PrintStream;
  18. import java.io.PrintWriter;
  19. import java.lang.reflect.Method;
  20. import java.sql.DriverManager;
  21. import java.sql.SQLException;
  22. /**
  23. * A SQLException subclass containing another Throwable
  24. *
  25. * @author Dirk Verbeeck
  26. * @version $Revision: 1.8 $ $Date: 2004/02/28 12:18:17 $
  27. */
  28. public class SQLNestedException extends SQLException {
  29. /* Throwable.getCause detection as found in commons-lang */
  30. private static final Method THROWABLE_CAUSE_METHOD;
  31. static {
  32. Method getCauseMethod;
  33. try {
  34. getCauseMethod = Throwable.class.getMethod("getCause", null);
  35. } catch (Exception e) {
  36. getCauseMethod = null;
  37. }
  38. THROWABLE_CAUSE_METHOD = getCauseMethod;
  39. }
  40. private static boolean hasThrowableCauseMethod() {
  41. return THROWABLE_CAUSE_METHOD != null;
  42. }
  43. /**
  44. * Holds the reference to the exception or error that caused
  45. * this exception to be thrown.
  46. */
  47. private Throwable cause = null;
  48. /**
  49. * Constructs a new <code>SQLNestedException</code> with specified
  50. * detail message and nested <code>Throwable</code>.
  51. *
  52. * @param msg the error message
  53. * @param cause the exception or error that caused this exception to be
  54. * thrown
  55. */
  56. public SQLNestedException(String msg, Throwable cause) {
  57. super(msg);
  58. this.cause = cause;
  59. if ((cause != null) && (DriverManager.getLogWriter() != null)) {
  60. DriverManager.getLogWriter().print("Caused by: ");
  61. cause.printStackTrace(DriverManager.getLogWriter());
  62. }
  63. }
  64. public Throwable getCause() {
  65. return this.cause;
  66. }
  67. public void printStackTrace(PrintStream s) {
  68. super.printStackTrace(s);
  69. if ((cause != null) && !hasThrowableCauseMethod()) {
  70. s.print("Caused by: ");
  71. this.cause.printStackTrace(s);
  72. }
  73. }
  74. public void printStackTrace(PrintWriter s) {
  75. super.printStackTrace(s);
  76. if ((cause != null) && !hasThrowableCauseMethod()) {
  77. s.print("Caused by: ");
  78. this.cause.printStackTrace(s);
  79. }
  80. }
  81. }