1. /*
  2. * @(#)PatternSyntaxException.java 1.12 03/01/23
  3. *
  4. * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.util.regex;
  8. import sun.security.action.GetPropertyAction;
  9. /**
  10. * Unchecked exception thrown to indicate a syntax error in a
  11. * regular-expression pattern.
  12. *
  13. * @author unascribed
  14. * @version 1.12, 03/01/23
  15. * @since 1.4
  16. * @spec JSR-51
  17. */
  18. public class PatternSyntaxException
  19. extends IllegalArgumentException
  20. {
  21. private final String desc;
  22. private final String pattern;
  23. private final int index;
  24. /**
  25. * Constructs a new instance of this class.
  26. *
  27. * @param desc
  28. * A description of the error
  29. *
  30. * @param regex
  31. * The erroneous pattern
  32. *
  33. * @param index
  34. * The approximate index in the pattern of the error,
  35. * or <tt>-1</tt> if the index is not known
  36. */
  37. public PatternSyntaxException(String desc, String regex, int index) {
  38. this.desc = desc;
  39. this.pattern = regex;
  40. this.index = index;
  41. }
  42. /**
  43. * Retrieves the error index.
  44. *
  45. * @return The approximate index in the pattern of the error,
  46. * or <tt>-1</tt> if the index is not known
  47. */
  48. public int getIndex() {
  49. return index;
  50. }
  51. /**
  52. * Retrieves the description of the error.
  53. *
  54. * @return The description of the error
  55. */
  56. public String getDescription() {
  57. return desc;
  58. }
  59. /**
  60. * Retrieves the erroneous regular-expression pattern.
  61. *
  62. * @return The erroneous pattern
  63. */
  64. public String getPattern() {
  65. return pattern;
  66. }
  67. private static String nl;
  68. static {
  69. nl = (String)java.security.AccessController
  70. .doPrivileged(new GetPropertyAction("line.separator"));
  71. }
  72. /**
  73. * Returns a multi-line string containing the description of the syntax
  74. * error and its index, the erroneous regular-expression pattern, and a
  75. * visual indication of the error index within the pattern.
  76. *
  77. * @return The full detail message
  78. */
  79. public String getMessage() {
  80. String nl = System.getProperty("line.separator");
  81. StringBuffer sb = new StringBuffer();
  82. sb.append(desc);
  83. if (index >= 0) {
  84. sb.append(" near index ");
  85. sb.append(index);
  86. }
  87. sb.append(nl);
  88. sb.append(pattern);
  89. if (index >= 0) {
  90. sb.append(nl);
  91. for (int i = 0; i < index; i++) sb.append(' ');
  92. sb.append('^');
  93. }
  94. return sb.toString();
  95. }
  96. }