After checking the JavaDocs for a method I was thinking of using, requiredNonNull, I stumbled across the first one with the single parameter (T obj).
However what is the actual purpose of this particular method with this signature? All it simply does is throw and NPE which I'm somewhat positive (as a I may be missing something obvious here) would be thrown anyway.
Throws:
NullPointerException - if obj is null
The latter actually makes sense in terms of debugging certain code, as the doc also states, it's primarily designed for parameter validation
public static <T> T requireNonNull(T obj,String message)
Checks that the specified object reference is not null and throws a customized NullPointerException if it is.
Therefore I can print specific information along with the NPE to make debugging a hell of a lot easier.
With this in mind I highly doubt I would come across a situation where I'd rather just use the former instead. Please do enlighten me.
tl;dr - Why would you ever use the overload which doesn't take a message.
A good principle when writing software is to catch errors as early as possible. The quicker you notice, for example, a bad value such as null being passed to a method, the easier it is to find out the cause and fix the problem.
If you pass null to a method that is not supposed to receive null, a NullPointerException will probably happen somewhere, as you already noticed. However, the exception might not happen until a few methods further down, and when it happens somewhere deep down, it will be more difficult to find the exact source of the error.
So, it's better when methods check their arguments up front and throw an exception as soon as they find an invalid value such as null.
edit - About the one-parameter version: even though you won't provide an error message, checking arguments and throwing an exception early will be more useful than letting the null pass down until an exception happens somewhere deeper down. The stack trace will point to the line where you used Objects.requireNonNull(...) and it should be obvious to you as a developer that that means you're not supposed to pass null. When you let a NullPointerException happen implicitly you don't know if the original programmer had the intent that the variable should not be null.
It is a utility method. Just a shortcut! (shortcut designers have their ways of doing their shortcut style).
Why throwing in the first place?
Security and Debugging.
Security: to not allow any illegal value in a sensitive place. (makes inner algorithm more sure about what are they doing and what are they having).
Debugging: for the program to die fast when something unexpected happens.
Related
I started using javax.annotation especially to warn the next developer who maybe will be working with my code in the future.
But while I was using the javax.annotation #Nonnull annotation, a question came into my mind:
If you mark f.e. a parameter of a method thorugh the #Nonnull annotation that it haves to have a value,
do you still need to handle the case, that the next developer who is using your code could be parsing null to your function?
If found one con argument and one pro argument to still handle the special cases.
con: The code is cleaner, especially if you have multiple parameters that you mark with #Nonnull
private void foo(#Nonnull Object o)
{
/*do something*/
}
vs
public void foo(Object o)
throws NullPointerException
{
if (o == null)
{
throw new NullPointerException("Given Object must have a value!");
}
/*do something*/
}
pro: It could cause unhandled errors if the next developer ignore the annotations.
This is an unsolved problem in the nullity annotation space. There are 2 viewpoints that sound identical but result, in fact, in the exact opposite. Given a parameter void foo(#NonNull String param), what does that imply?
It's compiler-checkable documentation that indicates you should not pass null as param here. It does not mean that it is impossible to do this, or that one ought to consider it impossible. Simply that one should not - it's compiler-checkable documentation that the method has no defined useful behaviour if you pass null here.
The compiler is extended to support these annotations to treat it as a single type - the type of param is #NonNull String - and the compiler knows what that means and will in fact ensure this. The type of the parameter is #NonNull String and therefore cannot be null, just like it can't be, say, an InputStream instance either.
Crucially, then, the latter means a null check is flagged as silly code, whereas the former means lack of a null check is marked as bad. Hence, opposites. The former considered a nullcheck a warnable offense (with something along the lines of param can never be null here), for the same reason this is silly code:
void foo(String arg) {
if (!(arg instanceof String)) throw new IllegalArgumentException("arg");
}
That if clause cannot possibly fire. The mindset of various nullchecker frameworks is identical here, and therefore flags it as silly code:
void foo(#NonNull String arg) {
if (arg == null) throw new NullPointerException("arg");
}
The simple fact is, plenty of java devs do not enable annotation-based nullity checking, and even if they did, there are at least 10 competing annotations and many of them mean completely different things, and work completely differently. The vast majority will not be using a checking framework that works as you think it should, therefore, the advice to remove the nullcheck because it is silly is actively a bad thing - you should add that nullcheck. The linting tools that flag this down are misguided; they want to pretend to live in a world where every java programmer on the planet uses their tool. This isn't try and is unlikely to ever become true, hence, wrong.
A few null checking frameworks are sort of living both lives and will allow you to test if an argument marked as #NonNull is null, but only if the if body starts with throw, otherwise it's flagged.
To answer your questions:
You should nullcheck. After all, other developers that use your code may not get the nullity warnings from the nullcheck tool (either other team members working on the same code base but using slightly different tools and/or configurations of those tools, or, your code is a library and another project uses it, a more obvious route to a situation with different tools/configs). The best way to handle a null failure is a compile time error. A close second is an exception that is clear about the problem and whose stack trace can be used to very quickly solve the bug. A distant third is random bizarreness that takes a whole to debug - and that explicit nullcheck means you get nice fallback: If for whatever reason the write-time tooling doesn't catch the problem, the check will then simply turn it into the second, still quite acceptable case of an exception at the point of failure that is clear about what happened and where to fix it.
Lombok's #NonNull annotation can generate it for you, if you want. Now you have the best of both worlds: Just a #NonNull annotation (no clutter) and yet a runtime exception if someone does pass null anyway (DISCLAIMER: I'm one of the core contributors to Lombok).
If your linting tool complains about 'pointless null check' on the line if (param == null) throw new NullPointerException("param");, find the option in the linting tool to exclude if-checks that result in throw statements. If the linting tool cannot be configured to ignore this case, do not use the linting tool, find a better one.
Note that modern JVMs will throw a NullPointerException with the name of the expression as message if you dereference a null pointer, which may obviate the need to write an explicit check. However, now you're dependent on that method always dereferencing that variable forever more; if ever someone changes it and e.g. assigns it to a field and returns, now you have a problem: It should have thrown the exception, in order to ensure the bug is found quickly and with an exception that explains what happened and where to go and fix the problem. Hence I wouldn't rely on the JVM feature for your NPEs.
Error messages should be as short as they can be whilst not skimping on detail. They should also not end in punctuation; especially exclamation marks. Every exception tends to be noteworthy enough to warrant an exclamation mark - but it gets tedious to read them, so do not add them. In fact, the proper thing to throw, is this: throw new NullPointerException("o"). - and you might want to rename that parameter to something more readable if you find o ugly. Parameters are mostly public API info (JVM-technically they are not, but javadoc does include them, which is the basis of API docs, so you should consider them public, and therefore, they should have clear names. Which you can then reuse). That exception conveys all relevant information to a programmer: The nature of the problem (null was sent to code that does not know how to handle this), and where (the stack trace does that automatically), and the specifics (which thing was null). Your message is much longer and doesn't add anything more. At best you can say your message might be understood by a non-coder, except this is both not true (as if a stack trace is something random joe computeruser is going to understand), and irrelevant (it's not like they can fix the problem even if they do know what it means). Using exception messages as UI output just doesn't work, so don't try.
You may want to adjust your style guides and allow braceless if statements provided that the if expression is simple (no && or ||). Possibly add an additional rule that the single statement is a control statement - break;, continue;, return (something);, or throw something;. This will significantly improve readability for multiparams. The point of a style guide is to create legible code. Surely this:
if (param1 == null) throw new NullPointerException("param1");
if (param2 == null) throw new NullPointerException("param2");
is far more legible, especially considering this method has more lines than just those two, than this:
if (param1 == null) {
throw new NullPointerException("param1");
}
if (param2 == null) {
throw new NullPointerException("param2");
}
Styleguides are just a tool. If your styleguide is leading to less productivity and harder to read code, the answer should be obvious. Fix or replace the tool.
This question already has answers here:
Java: How to check for null pointers efficiently
(14 answers)
Closed 8 years ago.
Sometimes I see developers using libraries like Guava’s Preconditions to validate the parameters for nulls in the beginning of a method. How is that different than getting NPE during runtime since a runtime exception occurs in either way?
EDIT: If there are good reasons, then shouldn't developers use libraries for null-check on all methods?
Some reasons are:
Prevents code from being run prior to the first time the variable (which could be null) is de-referenced.
You can have custom error messages, such as "myVar was null, I can't proceed further", or any relevant message which will look better in logs and more easily traceable. A normal NPE would be less readable in logs.
Readability of code is better (arguably) because a programmer reading this code will realize immediately that these values are expected to be non-null.
Ultimately it's a matter of taste IMO. I have seen programs that are inherently null safe and don't require pre-conditions at all.
There are various reasons. One big one, as mentioned in the comments, is to get the checking done up front before any work is done. It's also not uncommon for a method to have a code path in which a specific parameter is never dereferenced, in which case without upfront checking, invalid calls to the method may sometimes not produce an exception. The goal is to ensure they always produce an exception so that the bug is caught immediately. That said, I don't necessarily use checkNotNull if I'm going to immediately dereference the parameter on the next line or something.
There's also the case of constructors, where you want to checkNotNull before assigning a parameter to a field, but I don't think that's what you're talking about since you're talking about methods where the parameter will be used anyway.
I have a function which calculates the mean of a list passed as an argument. I would like to know which of Java exception should I throw when I try to compute the mean of a list of size 0.
public double mean (MyLinkedList<? extends Number> list)
{
if (list.isEmpty())
throw new ????????; //If I am not mistaken Java has some defined exception for this case
//code goes here
}
Thanks.
You can throw a new IllegalArgumentException().
Thrown to indicate that a method has been passed an illegal or inappropriate argument.
Just don't forget to pass a clear message as a first argument. This will really help you to understand what happend.
For example "Can't use mean on an empty List".
The question to ask yourself first is whether you should be throwing at all and then, if so, whether it should be a checked or unchecked exception.
Unfortunately, there's no industry best practice on deciding these things, as shown by this StackOverflow answer:
In Java, when should I create a checked exception, and when should it be a runtime exception?
Nevertheless, there are some key considerations:
Your design/vision for how this method is supposed to work (Is it reasonable/normal for the method to be called with 0-size list)?
Consistency with other methods in the class/package
Compliance with your applicable coding standard (if any)
My opinion:
Return Double.NAN or 0 If calling the method with a 0-size list is reasonable/expected/normal, I'd consider returning Double.NAN or 0 if 0 is appropriate for your problem domain.
Throw anIllegalArgumentException If my design says that checking for an empty List is strongly the responsibility of the caller and the documentation for the method is going to clearly state that it is the responsibility of the caller, then I'd use the standard unchecked IllegalArgumentException.
Throw a custom checked exception If the method is part of a statistics package or library where several statistics functions need to deal with an possible empty data set, I'd think this is an exception condition that is part of the problem domain. I'd create a custom (probably checked) exception (e.g. EmptyDataSetException) to be part of the class/package/library and use it across all applicable methods. Making it a checked exceptions helps remind the client to consider how to handle the condition.
You should create a new class that extends Exception and provides details specific to your error. For example you could create a class called EmptyListException that contains the details regarding your error. This could be a very simple exception class that takes no constructor arguments but maybe calls super("Cannot generate mean for an empty list"); to provide a custom message to the stack trace.
A lot of times this isn't done enough...one of my most hated code smells is when developers use a generic exception (even sometimes Exception itself) and pass a string message into the constructor. Doing this is valid but makes the jobs of those implementing your code much harder since they have to catch a generic exception when really only a few things could happen. Exceptions should have the same hierarchy as objects you use for data with each level providing more specific details. The more detailed the exception class, the more detailed and helpful the stack trace is.
I've found this site: Exceptional Strategies to be very useful when creating Exceptions for my applications.
IllegalArgumentException
How about NoSuchElementException. Although IllegalArgumentException might be better.
How about an ArithmeticException - the same as the runtime throws.
Are you currently throwing any other exceptions (or planning to?) Any of the previously mentioned exceptions are fine, or just create your own. The most important thing is propagating the message of what went wrong.
If there's a chance the 'catcher' of the exception might re-throw it, than you may want to investigate any other exceptions the 'catcher' might also throw.
I am not convinced you should be throwing an exception there at all; the average of "nothing" is "nothing" or 0 if you will. If the set is empty, you should simply return 0.
If you really MUST throw an exception, then IllegalStateException or IllegalArgumentException are your best choices.
I’m from a .NET background and now dabbling in Java.
Currently, I’m having big problems designing an API defensively against faulty input. Let’s say I’ve got the following code (close enough):
public void setTokens(Node node, int newTokens) {
tokens.put(node, newTokens);
}
However, this code can fail for two reasons:
User passes a null node.
User passes an invalid node, i.e. one not contained in the graph.
In .NET, I would throw an ArgumentNullException (rather than a NullReferenceException!) or an ArgumentException respectively, passing the name of the offending argument (node) as a string argument.
Java doesn’t seem to have equivalent exceptions. I realize that I could be more specific and just throw whatever exception comes closest to describing the situation, or even writing my own exception class for the specific situation.
Is this the best practice? Or are there general-purpose classes similar to ArgumentException in .NET?
Does it even make sense to check against null in this case? The code will fail anyway and the exception’s stack trace will contain the above method call. Checking against null seems redundant and excessive. Granted, the stack trace will be slightly cleaner (since its target is the above method, rather than an internal check in the HashMap implementation of the JRE). But this must be offset against the cost of an additional if statement, which, furthermore, should never occur anyway – after all, passing null to the above method isn’t an expected situation, it’s a rather stupid bug. Expecting it is downright paranoid – and it will fail with the same exception even if I don’t check for it.
[As has been pointed out in the comments, HashMap.put actually allows null values for the key. So a check against null wouldn’t necessarily be redundant here.]
The standard Java exception is IllegalArgumentException. Some will throw NullPointerException if the argument is null, but for me NPE has that "someone screwed up" connotation, and you don't want clients of your API to think you don't know what you're doing.
For public APIs, check the arguments and fail early and cleanly. The time/cost barely matters.
Different groups have different standards.
Firstly, I assume you know the difference between RuntimeExceptions (unchecked) and normal Exceptions (checked), if not then see this question and the answers. If you write your own exception you can force it to be caught, whereas both NullPointerException and IllegalArgumentException are RuntimeExceptions which are frowned on in some circles.
Secondly, as with you, groups I've worked with but don't actively use asserts, but if your team (or consumer of the API) has decided it will use asserts, then assert sounds like precisely the correct mechanism.
If I was you I would use NullPointerException. The reason for this is precedent. Take an example Java API from Sun, for example java.util.TreeSet. This uses NPEs for precisely this sort of situation, and while it does look like your code just used a null, it is entirely appropriate.
As others have said IllegalArgumentException is an option, but I think NullPointerException is more communicative.
If this API is designed to be used by outside companies/teams I would stick with NullPointerException, but make sure it is declared in the javadoc. If it is for internal use then you might decide that adding your own Exception heirarchy is worthwhile, but personally I find that APIs which add huge exception heirarchies, which are only going to be printStackTrace()d or logged are just a waste of effort.
At the end of the day the main thing is that your code communicates clearly. A local exception heirarchy is like local jargon - it adds information for insiders but can baffle outsiders.
As regards checking against null I would argue it does make sense. Firstly, it allows you to add a message about what was null (ie node or tokens) when you construct the exception which would be helpful. Secondly, in future you might use a Map implementation which allows null, and then you would lose the error check. The cost is almost nothing, so unless a profiler says it is an inner loop problem I wouldn't worry about it.
In Java you would normally throw an IllegalArgumentException
If you want a guide about how to write good Java code, I can highly recommend the book Effective Java by Joshua Bloch.
It sounds like this might be an appropriate use for an assert:
public void setTokens(Node node, int newTokens) {
assert node != null;
tokens.put(node, newTokens);
}
Your approach depends entirely on what contract your function offers to callers - is it a precondition that node is not null?
If it is then you should throw an exception if node is null, since it is a contract violation. If it isnt then your function should silently handle the null Node and respond appropriately.
I think a lot depends on the contract of the method and how well the caller is known.
At some point in the process the caller could take action to validate the node before calling your method. If you know the caller and know that these nodes are always validated then i think it is ok to assume you'll get good data. Essentially responsibility is on the caller.
However if you are, for example, providing a third party library that is distributed then you need to validate the node for nulls, etcs...
An illegalArugementException is the java standard but is also a RunTimeException. So if you want to force the caller to handle the exception then you need to provided a check exception, probably a custom one you create.
Personally I'd like NullPointerExceptions to ONLY happen by accident, so something else must be used to indicate that an illegal argument value was passed. IllegalArgumentException is fine for this.
if (arg1 == null) {
throw new IllegalArgumentException("arg1 == null");
}
This should be sufficient to both those reading the code, but also the poor soul who gets a support call at 3 in the morning.
(and, ALWAYS provide an explanatory text for your exceptions, you will appreciate them some sad day)
like the other : java.lang.IllegalArgumentException.
About checking null Node, what about checking bad input at the Node creation ?
I don't have to please anybody, so what I do now as canonical code is
void method(String s)
if((s != null) && (s instanceof String) && (s.length() > 0x0000))
{
which gets me a lot of sleep.
Others will disagree.
If I get a NullPointerException in a call like this:
someObject.getSomething().getSomethingElse().
getAnotherThing().getYetAnotherObject().getValue();
I get a rather useless exception text like:
Exception in thread "main" java.lang.NullPointerException
at package.SomeClass.someMethod(SomeClass.java:12)
I find it rather hard to find out which call actually returned null, often finding myself refactoring the code to something like this:
Foo ret1 = someObject.getSomething();
Bar ret2 = ret1.getSomethingElse();
Baz ret3 = ret2.getAnotherThing();
Bam ret4 = ret3.getYetAnotherOject();
int ret5 = ret4.getValue();
and then waiting for a more descriptive NullPointerException that tells me which line to look for.
Some of you might argue that concatenating getters is bad style and should be avoided anyway, but my Question is: Can I find the bug without changing the code?
Hint: I'm using eclipse and I know what a debugger is, but I can't figuer out how to apply it to the problem.
My conclusion on the answers:
Some answers told me that I should not chain getters one after another, some answers showed my how to debug my code if I disobeyed that advice.
I've accepted an answer that taught me exactly when to chain getters:
If they cannot return null, chain them as long as you like. No need for checking != null, no need to worry about NullPointerExceptions (be warned that chaining still violates the Law of Demeter, but I can live with that)
If they may return null, don't ever, never ever chain them, and perform a check for null values on each one that may return null
This makes any good advice on actual debugging useless.
NPE is the most useless Exception in Java, period. It seems to be always lazily implemented and never tells exactly what caused it, even as simple as "class x.y.Z is null" would help a lot in debugging such cases.
Anyway, the only good way I've found to find the NPE thrower in these cases is the following kind of refactoring:
someObject.getSomething()
.getSomethingElse()
.getAnotherThing()
.getYetAnotherObject()
.getValue();
There you have it, now NPE points to correct line and thus correct method which threw the actual NPE. Not as elegant solution as I'd want it to be, but it works.
The answer depends on how you view (the contract of) your getters. If they may return null you should really check the return value each time. If the getter should not return null, the getter should contain a check and throw an exception (IllegalStateException?) instead of returning null, that you promised never to return. The stacktrace will point you to the exact getter. You could even put the unexpected state your getter found in the exception message.
In IntelliJ IDEA you can set exceptionbreakpoints. Those breakpoints fire whenever a specified exception is thrown (you can scope this to a package or a class).
That way it should be easy to find the source of your NPE.
I would assume, that you can do something similar in netbeans or eclipse.
EDIT: Here is an explanation on how to add an exceptionbreakpoint in eclipse
If you find yourself often writing:
a.getB().getC().getD().getE();
this is probably a code smell and should be avoided. You can refactor, for example, into a.getE() which calls b.getE() which calls c.getE() which calls d.getE(). (This example may not make sense for your particular use case, but it's one pattern for fixing this code smell.)
See also the Law of Demeter, which says:
Your method can call other methods in its class directly
Your method can call methods on its own fields directly (but not on the fields' fields)
When your method takes parameters, your method can call methods on those parameters directly.
When your method creates local objects, that method can call methods on the local objects.
Therefore, one should not have a chain of messages, e.g. a.getB().getC().doSomething(). Following this "law" has many more benefits apart from making NullPointerExceptions easier to debug.
I generally do not chain getters like this where there is more than one nullable getter.
If you're running inside your ide you can just set a breakpoint and use the "evaluate expression" functionality of your ide on each element successively.
But you're going to be scratching your head the moment you get this error message from your production server logs. So best keep max one nullable item per line.
Meanwhile we can dream of groovy's safe navigation operator
Early failure is also an option.
Anywhere in your code that a null value can be returned, consider introducing a check for a null return value.
public Foo getSomething()
{
Foo result;
...
if (result == null) {
throw new IllegalStateException("Something is missing");
}
return result;
}
Here's how to find the bug, using Eclipse.
First, set a breakpoint on the line:
someObject.getSomething().getSomethingElse().
getAnotherThing().getYetAnotherObject().getValue();
Run the program in debug mode, allow the debugger to switch over to its perspective when the line is hit.
Now, highlight "someObject" and press CTRL+SHIFT+I (or right click and say "inspect").
Is it null? You've found your NPE. Is it non-null?
Then highlight someObject.getSomething() (including the parenthesis) and inspect it.
Is it null? Etc. Continue down the chain to figure out where your NPE is occurring, without having to change your code.
You may want to refer to this question about avoiding != null.
Basically, if null is a valid response, you have to check for it. If not, assert it (if you can). But whatever you do, try and minimize the cases where null is a valid response for this amongst other reasons.
If you're having to get to the point where you're splitting up the line or doing elaborate debugging to spot the problem, then that's generally God's way of telling you that your code isn't checking for the null early enough.
If you have a method or constructor that takes an object parameter and the object/method in question cannot sensibly deal with that parameter being null, then just check and throw a NullPointerException there and then.
I've seen people invent "coding style" rules to try and get round this problem such as "you're not allowed more than one dot on a line". But this just encourages programming that spots the bug in the wrong place.
Chained expressions like that are a pain to debug for NullPointerExceptions (and most other problems that can occur) so I would advise you to try and avoid it. You have probably heard that enough though and like a previous poster mentioned you can add break points on the actual NullPointerException to see where it occurred.
In eclipse (and most IDEs) you can also use watch expressions to evaluate code running in the debugger. You do this bu selecting the code and use the contet menu to add a new watch.
If you are in control of the method that returns null you could also consider the Null Object pattern if null is a valid value to return.
Place each getter on its own line and debug. Step over (F6) each method to find which call returns null