Search code examples
javaregexvalidationnotnull

Why does Java java.util.regex Pattern Matcher Throw Runtime Exceptions?


The following code throw a runtime exception in my project

Pattern pattern = Pattern.compile("");
Matcher matcher = pattern.matcher(null);

Uncaught exception: java.lang.NullPointerException: Cannot invoke "java.lang.CharSequence.length()" because "this.text" is null at java.base/java.util.regex.Matcher.getTextLength(Matcher.java:1769) at java.base/java.util.regex.Matcher.reset(Matcher.java:415) at java.base/java.util.regex.Matcher.(Matcher.java:252) at java.base/java.util.regex.Pattern.matcher(Pattern.java:1134)

In my IDE it says this method is marked @NotNull (see below) which is I assume why it's throwing an exception because my understanding is that if there's a "NotNull validator" on my Classpath it will do this.

My questions are:

  1. Where is the @NotNull annotation even coming from? I don't see it in the JavaDoc - is that actually part of the Java SDK?
  2. How do I know what validator is throwing that exception?
  3. If it's not the validator then why is is throwing an Exception that's not mentioned in the method signature?

enter image description here


Solution

    1. @NotNull is a Code-Contract Annotation added by IntelliJ.

    2. The annotation (or its potential validator) is not the one throwing the exception, it only hints you about potential issues at design-time but the code still compiles. Instead, Matcher.getTextLength() is throwing the exception at runtime, as shown in the stack trace.

    3. The exception being thrown is a NullPointerException, subclass of RuntimeException which do not need to be declared in the methods' signatures, in contrary to so-called checked exceptions (it would be pretty verbose to specify each time a NullPointerException can be thrown, although it may still be interesting to make it explicit in some cases).