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:
@NotNull
is a Code-Contract Annotation added by IntelliJ.
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.
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).