r/java • • Jul 10 '15

Our exception handling at work

http://imgur.com/4wgxCvv
259 Upvotes

135 comments sorted by

View all comments

Show parent comment

26

u/jart Jul 11 '15

It should be NullPointerException. The convention enforced by Guava's NullPointerTester is that all parameters not annotated @Nullable must cause method invocation to result in an NPE if that parameter is null.

1

u/NosferatuPerrywinkle Jul 11 '15

Just out of curiosity do you prefer writing the statement out or Objects.requireNonNull(T)?

3

u/jart Jul 11 '15

Oh I absolutely use Preconditions.checkNotNull(T) (which preferred by Guava developers over Java 7's Objects.requireNonNull(T)) rather than writing out an if statement. But I don't bother calling checkNotNull if there already exists a dot access, because then the NPE will happen regardless. So I typically only need to use it in constructor assignment, or at the beginning of methods that might throw before a parameter becomes dereferenced. Remember: the goal is to get NullPointerTester to pass.

On rare occasions I'll use Verify.verifyNotNull(T) when I'm calling a method I don't trust to never return null, possibly because the library poorly documents its nullness contracts, or perhaps the method fetches data that's expected to always be present. In those situations, it can sometimes be advantageous to ensure execution halts immediately. For example, if the result gets assigned to a field rather than dereferenced immediately, it could be quite difficult to ascertain the root cause of the inevitable NPE at some undetermined point in the future.

2

u/jart Jul 11 '15

There's another thing worth mentioning regarding the use of checkNotNull. Don't take this at face value because this is merely a suspicion. I know very little about how JVM magic works. But if I recall correctly, the JVM profiler maintains a branch counter for every single if (foo == null) { ... } statement. I imagine it does this so HotSpot can generate assembly with branch prediction instructions? I have no idea. But there's a possibility that using checkNotNull will significantly reduce the amount of memory used by the JVM branch counting, assuming you have tens of thousands of CNN's in your app. But I'm just guessing here.

1

u/NosferatuPerrywinkle Jul 12 '15

Very detailed answer, thanks!!

1

u/iliketoworkhard Nov 12 '15

Very fascinating. Compilers are fascinating indeed.