Best practise in catching and throwing nullpointerexception? - java

It seems like it is not a good idea to catch a nullpointerexception. If that's the case, why is it thrown by methods? Should it just be caught with Exception?
Also, if I encounter a parameter which is null (can either be primitive type like string or a class with fields), how should I handle it? (assumingly not throw npe)?
Thanks

It is a runtime exception, thus is not intended to be caught deep inside your program code, only [update] at (or close to) the top level or [/update] by the JVM. Since runtime exceptions signal serious problems (typically grave programming errors, configuration/integration problems etc.), it is best to let them propagate to the top, which typically makes the whole thread fail spectacularly. This gives a strong signal that something is wrong and needs to be fixed ASAP.
See also Is Catching a Null Pointer Exception a Code Smell?.
Also, if I encounter a parameter which is null [...], how should I handle it?
It is OK to throw a NPE in general. However, depending on the circumstances, you may also consider IllegalArgumentException, or using an assertion. See also
Is it okay to throw NullPointerException programatically ?
IllegalArgumentException or NullPointerException for a null parameter?

A nullpointerexception usually indicates a programmer error. You won't catch a null pointer exception if you don't expect such a programmer error. For instance, say you implement a method myMethod with one parameter of type P.
void myMethod(P x)
Let's say you don't expect the parameter x to be null. In this case you might not check for null. Why? because you assume that the programmer who is using your method will use it properly and won't pass null. I'm not saying whether you should or shouldn't check for null in such cases. I'm just trying to answer why sometimes a null pointer exception is thrown by a method and isn't supposed to be caught. Here's why: Your method might throw a null pointer exception because someone didn't use it right (passed null). The programmer who is using your method might know that if the method is being used wrong it might throw a nullpointerexcetption. But even if he uses your method wrong the exception won't be caught because everyone assumes that the method isn't misused.
Your second question: First, a String is an Object, not a primitive type. Second, primitives can't be null (primitives are ints, doubles, floats, chars, booleans and some others). Now, if you encounter a parameter which is null and it shouldn't be null (in other words you received an illegal argument) you have some choices:
Throw an IllegalArgumentException indicating the parameter is null and your method expects it not to be null.
Don't do anything. Assume your method is being used correctly (in other words, assume no programmer errors).
Use assertions: assert(x != null);
I personally am not a fan of defensive programming and usually prefer the second option. But still, if I want to ensure some invariants on my variables I'm using assertions. But these are just my habits and others probably disagree.

This answer may be lengthy but I think it worth it.
It seems like it is not a good idea to catch a nullpointerexception.
You're right, you should not catch NullPointerException, nor any runtime exception.
If that's the case, why is it thrown by methods? Should it just be caught with Exception?
It is used to indicate a programming error was found. These programming errors could and should be fixed with code ( That is, they're preventable )
Also, if I encounter a parameter which is null how should I handle it? [...](assumingly not throw npe)?
It depends on what you want to do with it. For some logic, a null value may be allowed. If that's the case, you validate the presence of null and do something about it, either provide a default value or avoid sending messaged to the null.
For instance. Let's say you have a billing information system, and you have this code where you save the customer information, and you may optionally save customer extra information.
In this case, the optional message may be null, and your code should validate the presence of it.
For instance:
/**
* ...
* #param - OptionalMessage may be null, include anything else you wan to save.
*/
public void sendCustomerInformation( Customer c , OptionalMessage optionalMessage ) {
SomeMessage message = SomeMessage.createMessage();
message.setHeader( c.name() );
message.setCustomerInformation( c );
if( optionalMessage != null ) { // is optional? handle it
message.add( optionalMessage.status() );
message.add( optionalMessage.summary() );
message.add( optionalMessage.message() );
}
}
}
You validate the presence of null and document it.
But this same code also has a customer as parameter, in this case you could:
a) Do nothing
b) Validate it also
c) Throw a different exception according to the level of abstraction at this level.
For instance, the above code, does a) nothing. This will result in a NullPointerException where the code c.name() is invoked, and this should be catched early in the development tests. Also, it should be documented, in the param and the throws in the javadoc.
/**
* ...
* #param c - The customer whose information is to be sent. NotNull
* ...
* #throws NullPointerException if the customer is null
*/
public void sendCustomerInformation( Customer c , OptionalMessage optionalMessage ) {
SomeMessage message = SomeMessage.createMessage();
...
If somebody invokes this method with a null, the Npe will indicate they have coded something wrong. Plus, the Npe, will say very quickly what and where the coding error was ( when invoking the sendCustomerInformation with null customer.
option b) Validate it. It may be the case, when you may allow to handle a null customer ( it doesn't make sense but, it is an option )
In this case you may validate it and return prematurely ( in a I'm done fashion )
public void sendCustomerInformation( Customer c , OptionalMessage optionalMessage ) {
if( cusomer == null ) { return; // I'm done! }
// else
SomeMessage message = ...
..
}
Or may create a replacement:
public void sendCustomerInformation( Customer c , OptionalMessage optionalMessage ) {
if( cusomer == null ) { c = new EmptyCustomer() ;}
// else
SomeMessage message = ...
..
}
option c) This is similar to a, but, in this case you throw the exception according to the level of abstraction. For instance, if this is going to be shown to the final user in a GUI or something, it may not make sense to just throw the Npe:
public void sendCustomerInformation( Customer c , OptionalMessage optionalMessage ) {
if( cusomer == null ) {
// oh oh something went wrong.
log.fatal("Invalid argument on \"sendCustomerInformation\" );
throw new MyApplicationException("Dear customer, the information yada yaa");
}
...
If this is some sort of invalida state in the app:
public void sendCustomerInformation( Customer c , OptionalMessage optionalMessage ) {
if( cusomer == null ) {
// wait a minute, how could... why did.. what?
throw new IllegalStateException("Hey, I got null on sendCustomerInformation and this shouldn't happen");
}
...
Because maybe the app is responsible to keep that object/parameter in a valid shape.
Conclusion
So it depends on the scenario, but in general terms, a NullPointerException ( and most RuntimeExceptions ) indicate something that could be fixed with code ( that are a programmer mistake ) and you can always do something about it. There are cases where you can't do something about it, the best thing you can do, is to let it pop.
I hope this helps.
See also: Exception other than RuntimeException

Throw an IllegalArgumentException rather than a NP if someone illegally passes Null to your method. That better describes the error.

NPE and RuntimeExceptions in general are mostly thrown when there's a coding error, that's why catching them isn't considered to be a good idea. What should be done instead is fixing the code that can't handle the null input.
Which is the second part of your question, how null input should be handled. It depends entirely on what you're reasonably expecting in your code.
Let's say that you read data from a database table and read a null value from a nullable column, that's definitely not an exceptional case, so your code should handle it as its appropiate from a business point of view (e.g. ignore the entire row, prompt the user to enter a value or just use a dummy value).
However if you're reading a null value from a non-nullable column, say a primary key, you should throw an application-specific exception, which is (hopefully) handled by your application's UI.
So the answer is really as simple as: if null is a value that can happen during normal operation, deal with it accordingly, if not, throw a checked business exception instead of an NPE.

The most probable circumstances under which you might want to catch an NPE is when you are implementing a kind of framework, that is, you do NOT want to terminate your application, but report the error, and you have a way of (sensibly) continue in your application.

To avoid null-checks in your code, in most cases it's appropriate to return a null-object or an empty list/map/set instead of null.

Related

Is using IllegalArgumentException correct if field is wrong? [duplicate]

I'm worried that this is a runtime exception so it should probably be used sparingly.
Standard use case:
void setPercentage(int pct) {
if( pct < 0 || pct > 100) {
throw new IllegalArgumentException("bad percent");
}
}
But that seems like it would force the following design:
public void computeScore() throws MyPackageException {
try {
setPercentage(userInputPercent);
}
catch(IllegalArgumentException exc){
throw new MyPackageException(exc);
}
}
To get it back to being a checked exception.
Okay, but let's go with that. If you give bad input, you get a runtime error. So firstly that's actually a fairly difficult policy to implement uniformly, because you could have to do the very opposite conversion:
public void scanEmail(String emailStr, InputStream mime) {
try {
EmailAddress parsedAddress = EmailUtil.parse(emailStr);
}
catch(ParseException exc){
throw new IllegalArgumentException("bad email", exc);
}
}
And worse - while checking 0 <= pct && pct <= 100 the client code could be expected to do statically, this is not so for more advanced data such as an email address, or worse, something that has to be checked against a database, therefore in general client code cannot pre-validate.
So basically what I'm saying is I don't see a meaningful consistent policy for the use of IllegalArgumentException. It seems it should not be used and we should stick to our own checked exceptions. What is a good use case to throw this?
The API doc for IllegalArgumentException:
Thrown to indicate that a method has been passed an illegal or inappropriate argument.
From looking at how it is used in the JDK libraries, I would say:
It seems like a defensive measure to complain about obviously bad input before the input can get into the works and cause something to fail halfway through with a nonsensical error message.
It's used for cases where it would be too annoying to throw a checked exception (although it makes an appearance in the java.lang.reflect code, where concern about ridiculous levels of checked-exception-throwing is not otherwise apparent).
I would use IllegalArgumentException to do last ditch defensive argument checking for common utilities (trying to stay consistent with the JDK usage). Or where the expectation is that a bad argument is a programmer error, similar to an NullPointerException. I wouldn't use it to implement validation in business code. I certainly wouldn't use it for the email example.
When talking about "bad input", you should consider where the input is coming from.
Is the input entered by a user or another external system you don't control, you should expect the input to be invalid, and always validate it. It's perfectly ok to throw a checked exception in this case. Your application should 'recover' from this exception by providing an error message to the user.
If the input originates from your own system, e.g. your database, or some other parts of your application, you should be able to rely on it to be valid (it should have been validated before it got there). In this case it's perfectly ok to throw an unchecked exception like an IllegalArgumentException, which should not be caught (in general you should never catch unchecked exceptions). It is a programmer's error that the invalid value got there in the first place ;) You need to fix it.
Throwing runtime exceptions "sparingly" isn't really a good policy -- Effective Java recommends that you use checked exceptions when the caller can reasonably be expected to recover. (Programmer error is a specific example: if a particular case indicates programmer error, then you should throw an unchecked exception; you want the programmer to have a stack trace of where the logic problem occurred, not to try to handle it yourself.)
If there's no hope of recovery, then feel free to use unchecked exceptions; there's no point in catching them, so that's perfectly fine.
It's not 100% clear from your example which case this example is in your code, though.
Treat IllegalArgumentException as a preconditions check, and consider the design principle: A public method should both know and publicly document its own preconditions.
I would agree this example is correct:
void setPercentage(int pct) {
if( pct < 0 || pct > 100) {
throw new IllegalArgumentException("bad percent");
}
}
If EmailUtil is opaque, meaning there's some reason the preconditions cannot be described to the end-user, then a checked exception is correct. The second version, corrected for this design:
import com.someoneelse.EmailUtil;
public void scanEmail(String emailStr, InputStream mime) throws ParseException {
EmailAddress parsedAddress = EmailUtil.parseAddress(emailStr);
}
If EmailUtil is transparent, for instance maybe it's a private method owned by the class under question, IllegalArgumentException is correct if and only if its preconditions can be described in the function documentation. This is a correct version as well:
/** #param String email An email with an address in the form abc#xyz.com
* with no nested comments, periods or other nonsense.
*/
public String scanEmail(String email)
if (!addressIsProperlyFormatted(email)) {
throw new IllegalArgumentException("invalid address");
}
return parseEmail(emailAddr);
}
private String parseEmail(String emailS) {
// Assumes email is valid
boolean parsesJustFine = true;
// Parse logic
if (!parsesJustFine) {
// As a private method it is an internal error if address is improperly
// formatted. This is an internal error to the class implementation.
throw new AssertError("Internal error");
}
}
This design could go either way.
If preconditions are expensive to describe, or if the class is intended to be used by clients who don't know whether their emails are valid, then use ParseException. The top level method here is named scanEmail which hints the end user intends to send unstudied email through so this is likely correct.
If preconditions can be described in function documentation, and the class does not intent for invalid input and therefore programmer error is indicated, use IllegalArgumentException. Although not "checked" the "check" moves to the Javadoc documenting the function, which the client is expected to adhere to. IllegalArgumentException where the client can't tell their argument is illegal beforehand is wrong.
A note on IllegalStateException: This means "this object's internal state (private instance variables) is not able to perform this action." The end user cannot see private state so loosely speaking it takes precedence over IllegalArgumentException in the case where the client call has no way to know the object's state is inconsistent. I don't have a good explanation when it's preferred over checked exceptions, although things like initializing twice, or losing a database connection that isn't recovered, are examples.
As specified in oracle official tutorial , it states that:
If a client can reasonably be expected to recover from an exception,
make it a checked exception. If a client cannot do anything to recover
from the exception, make it an unchecked exception.
If I have an Application interacting with database using JDBC , And I have a method that takes the argument as the int item and double price. The price for corresponding item is read from database table. I simply multiply the total number of item purchased with the price value and return the result. Although I am always sure at my end(Application end) that price field value in the table could never be negative .But what if the price value comes out negative? It shows that there is a serious issue with the database side. Perhaps wrong price entry by the operator. This is the kind of issue that the other part of application calling that method can't anticipate and can't recover from it. It is a BUG in your database. So , and IllegalArguementException() should be thrown in this case which would state that the price can't be negative.
I hope that I have expressed my point clearly..
Any API should check the validity of the every parameter of any public method before executing it:
void setPercentage(int pct, AnObject object) {
if( pct < 0 || pct > 100) {
throw new IllegalArgumentException("pct has an invalid value");
}
if (object == null) {
throw new IllegalArgumentException("object is null");
}
}
They represent 99.9% of the times errors in the application because it is asking for impossible operations so in the end they are bugs that should crash the application (so it is a non recoverable error).
In this case and following the approach of fail fast you should let the application finish to avoid corrupting the application state.

Code conventions - good or bad practice to catch exception instead of if-checking previously?

I want to set an Integer to a specific value, which is 0 or the attribute found in another class. Since instances of this class are stored in a Map of Lists, but this map may be null at the point, I wonder which of the both ways to handle this are better.
Integer value = 0;
if (myMap != null &&
myMap.get(keyForList) != null &&
myMap.get(keyForList).get(0) != null) {
value = myMap.get(keyForList).get(0).getAttribute();
}
Or the way which I would consider better and more efficient:
Integer value = 0;
try {
value = myMap.get(keyForList).get(0).getAttribute();
} catch (NullPointerException e) {
// without doing anything value is 0 as expected
}
Thanks for any help!
The standard advice is that exceptions shouldn't be used for flow control. They're relatively heavy-weight, break the standard flow of control and consequently can be difficult to follow. They should be used for exceptional circumstances.
That's not to say that you can't use them to recover from conditions, but if it's easy/more explicit to check for (say) null or zero, then you should do that in preference.
I would note (however) that Java is verbose and doesn't have simple operations for handling defaults/nulls in code such as:
Integer result = a.getB().getC().getD();
As such, my advice is:
check out the null object pattern, which means that you can get away with no null checks in the above scenario
code like the above points to a real lack of OO functionality. The code above should get object a itself to get b, and object b would get c, and so on. In it's current form it breaks the Law of Demeter and exposes to you how a, b, c etc are composed. Remember that OO is about getting objects to do things for you, not having them tell you what they're composed of and having you do it yourself.
Avoid exceptions if there are no unexpected events in the code. I would suggest the following:
Integer value = 0;
if (myMap != null)
{
if(myMap.get(keyForList) != null && !myMap.get(keyForList).isEmpty())
value = myMap.get(keyForList).get(0).getAttribute();
else
System.out.println("There is no key " + keyForList + " in my map!");
}
else
System.out.println("My map is null!");
This way you'll know for sure where the null value is (useful for debugging purposes).
Exceptions are much more expensive than if, so it's usually preferable to avoid them when possible, especially so if there's only one statement in the try{} block.
However, when you can wrap lots of code inside try{}, then exceptions start making more sense. I think this is starting to be case in your example code. Even though you have just one if statement, it has complex condition. Avoiding that with try-catch is probably better.
Exceptions are fine for catching errors, such as badly formed input, when it's expected that input normally is valid.
Detecting input (like method argument) null pointer by catching NullPointerException is rarely good idea. Either have if before, or just let the exception get thrown out of your method without intervening, if it's caller's responsiblity (it may even be sensible to detect null pointer with if and throw NullPointerException yourself, without calling anything else).
Exceptions are for when normal flow of execution fails, and we can't continue.
With If-else code does not break

Methods returning values vs. those which don't

When you write methods you almost always have to check for things that must be valid.
Lets say you need to throw an IllegalArgumentException if the price argument on a method is invalid. Because I want to break my programs into small pieces I make a private method for it. However is it best practice to create a method that is named something like validatePrize and returns a boolean which I then check in an if statement where I invoke the validatePrize method, and then throw an IllegalArgumentException?
Or is it better that the method does not return anything and also throws the exception?
I would say the answer to this is mainly based on preference. If you want a reusable function which doesn't throw an exception when called, then pick the validatePrize with a boolean return. If you are only using it to check for an exception, then use the validatePrize which throws an exception. In this case I would say that the validatePrize which throws an exception would be more suited, as it can be used for exception handling from outside the class itself.
It totally depends.
Firstly, validatePrize doesn't sound like a boolean method, so IMO it shouldn't return anything.
If you have a bunch of guard clauses, throw an exception. If you need validation across the app for the same collection of attributes, make it a method–but that method can also be used as part of the guard.
Since you already know that a negative value is an invalid argument, you can guard against it by doing :
if(val < 0)
{
return false;
}
I've read in books that guarding against such a situation is the best way to go. It isn't or doesn't meet "an exception criteria". So yeah I would just return a boolean.
Some like to throw exceptions though, but it is up to you.
If you do delegate the check to a method, you could as well throw an exception from that method directly to avoid clutter code in your constructor. This is a typical approach used by guava's Preconditions:
this.value = Preconditions.checkNotNull(value, "value must not be null");
this line will throw an NullPointerException with the associated message if the argument is null. If the argument is not null, it returns the argument which enables to check and assign the argument in one line.
If you are interested, this is what the code looks like:
public static <T> T checkNotNull(T reference, Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
You could use a similar approach for your use case.
My own opinion about this is that exceptions should only be thrown if something in unexpected. A null pointer can be this, or a negative number for an ID (which should always be positive). Basically, an exception is used to show a problem inside your program. If you're simply validating a user's input, use booleans and tests.

Should we always check each parameter of method in java for null in the first line?

Every method accepts a set of parameter values. Should we always validate the non-nullness of input parameters or allow the code to fail with classic RunTimeException?
I have seen a lot of code where people don't really check the nullness of input parameters and just write the business logic using the parameters. What is the best way?
void public( String a, Integer b, Object c)
{
if( a == null || b == null || c == null)
{
throw new RunTimeException("Message...");
}
.....business logic.....
}
The best way is to only check when necessary.
If your method is private, for example, so you know nobody else is using it, and you know you aren't passing in any nulls, then no point to check again.
If your method is public though, who knows what users of your API will try and do, so better check.
If in doubt, check.
If the best you can do, however, is throw a NullPointerException, then may not want to check. For example:
int getStringLength(String str) {
return str.length();
}
Even if you checked for null, a reasonable option would be throwing a NullPointerException, which str.length() will do for you anyways.
No. It's standard to assume that parameters will not be null and that a NullPointerException will be thrown otherwise. If your method allows a parameter to be null, you should state that in your api.
It's an unfortunate aspect of Java that references can be null and there is no way to specify in the language that they are not.
So generally yes, don't make up an interpretation for null and don't get into a situation where an NPE might be thrown later.
JSR305 (now inactive) allowed you to annotate parameters to state that they should not be given nulls.
void fn(#Nonnull String a, #Nonnull Integer b, #Nonnull Object c) {
Verbose, but that's Java for you. There are other annotation libraries and checkers that do much the same, but are non-standard.
(Note about capitalisation: When camel-casing words of the form "non-thing", the standard is not to capitalise the route word unless it is the name of a class. So nonthing and nonnull.)
Annotations also don't actually enforce the rule, other than when a checker is run. You can statically include a method to do the checking:
public static <T> T nonnull(T value) {
if (value == null) {
throwNPE();
}
return value;
}
private static void throwNPE() {
throw new NullPointerException();
}
Returning the value is handy in constructors:
import static pkg.Check.nonnull;
class MyClass {
#Nonnull private final String thing;
public MyClass(#Nonnull String thing) {
this.thing = nonnull(thing);
}
...
I don't see a great deal of point in doing this. You're simply replicating behaviour that you'd get for free the first time you try to operate on a, b or c.
It depends if you expect any of your arguments to be null - more precisely, if your method can still make a correct decision if some parameters are null.
If not, it's good practice to check for null and raise an exception, because otherwise you'll get a NullPointerException, which you should never catch, as its appearance always indicates that you forgot to check your variables in your code. (and if you catch it, you might miss other occurrences of it being thrown, and you may introduce bugs).
On the other hand, if you throw RunTimeException or some other custom exception, you could then handle it somewhere on the upstream, so that you have more control over what goes on.
Yes, public methods should scrub the input, especially if bad input could cause problems within your method's code. It's a good idea to fail fast; that is, check as soon as possible. Java 7 added a new Objects class that makes it easy to check for null parameters and include a customized message:
public final void doSomething(String s)
{
Objects.requireNonNull(s, "The input String cannot be null");
// rest of your code goes here...
}
This will throw a NullPointerException.
Javadocs for the Objects class: http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html
It depends on what your code is trying to do and the situation in which you want to throw an Exception. Sometime you will want your method to always throw an Exception if your method will not be able to work properly with null values. If your method can work around null values then its probably not necessary to throw an Exception.
Adding too many checked Exceptions can make for very convoluted and complicated code. This was the reason that they were not included in C#.
No, you shouldn't do that universally.
My preferences, in order, would be:
Do something sensible with the null. The sensible thing to do depends entirely on the situation, but throwing a custom exception should not be your first choice.
Use an assertion to check for null and test thoroughly, eliminating any situations in which null input is produced since - a.k.a bugs.
For public APIs, document that null isn't allowed and let it fail with an NPE.
You should never throw a runtime exception unless it is truly a fatal condition for the operation of the system, such as missing critical runtime parameters, but even then this is questionable as the system should just not start.
What are the business rules? Is null allowed for the field? Is it not?
In any case, it is always good practice to CHECK for nulls on ANY parameters passed in before you attempt to operate on them, so you don't get NullPointerExceptions when someone passes you bad data.
If you don't know whether you should do it, the chances are, you don't need to do it.
JDK sources, and Joshua Bloch's book, are terrible examples to follow, because they are targeting very different audiences. How many of us are writing public APIs for millions of programmers?

Should a retrieval method return 'null' or throw an exception when it can't produce the return value? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I am using java language,I have a method that is supposed to return an object if it is found.
If it is not found, should I:
return null
throw an exception
other
Which is the best practise or idiom?
If you are always expecting to find a value then throw the exception if it is missing. The exception would mean that there was a problem.
If the value can be missing or present and both are valid for the application logic then return a null.
More important: What do you do other places in the code? Consistency is important.
Only throw an exception if it is truly an error. If it is expected behavior for the object to not exist, return the null.
Otherwise it is a matter of preference.
As a general rule, if the method should always return an object, then go with the exception. If you anticipate the occasional null and want to handle it in a certain way, go with the null.
Whatever you do, I highly advise against the third option: Returning a string that says "WTF".
If null never indicates an error then just return null.
If null is always an error then throw an exception.
If null is sometimes an exception then code two routines. One routine throws an exception and the other is a boolean test routine that returns the object in an output parameter and the routine returns a false if the object was not found.
It's hard to misuse a Try routine. It's real easy to forget to check for null.
So when null is an error you just write
object o = FindObject();
When the null isn't an error you can code something like
if (TryFindObject(out object o)
// Do something with o
else
// o was not found
I just wanted to recapitulate the options mentioned before, throwing some new ones in:
return null
throw an Exception
use the null object pattern
provide a boolean parameter to you method, so the caller can chose if he wants you to throw an exception
provide an extra parameter, so the caller can set a value which he gets back if no value is found
Or you might combine these options:
Provide several overloaded versions of your getter, so the caller can decide which way to go. In most cases, only the first one has an implementation of the search algorithm, and the other ones just wrap around the first one:
Object findObjectOrNull(String key);
Object findObjectOrThrow(String key) throws SomeException;
Object findObjectOrCreate(String key, SomeClass dataNeededToCreateNewObject);
Object findObjectOrDefault(String key, Object defaultReturnValue);
Even if you choose to provide only one implementation, you might want to use a naming convention like that to clarify your contract, and it helps you should you ever decide to add other implementations as well.
You should not overuse it, but it may be helpfull, espeacially when writing a helper Class which you will use in hundreds of different applications with many different error handling conventions.
Use the null object pattern or throw an exception.
Advantages of throwing an exception:
Cleaner control flow in your calling code. Checking for null injects a conditional branch which is natively handled by try/catch. Checking for null doesn't indicate what it is you're checking for - are you checking for null because you're looking for an error you're expecting, or are you checking for null so you don't pass it further on downchain?
Removes ambiguity of what "null" means. Is null representative of an error or is null what is actually stored in the value? Hard to say when you only have one thing to base that determination off of.
Improved consistency between method behavior in an application. Exceptions are typically exposed in method signatures, so you're more able to understand what edge cases the methods in an application account for, and what information your application can react to in a predictable manner.
For more explanation with examples, see: http://metatations.com/2011/11/17/returning-null-vs-throwing-an-exception/
Be consistent with the API(s) you're using.
Just ask yourself: "is it an exceptional case that the object is not found"? If it is expected to happen in the normal course of your program, you probably should not raise an exception (since it is not exceptional behavior).
Short version: use exceptions to handle exceptional behavior, not to handle normal flow of control in your program.
-Alan.
it depends if your language and code promotes:
LBYL (look before you leap)
or
EAFP (easier to ask forgiveness than permission)
LBYL says you should check for values (so return a null)
EAFP says to just try the operation and see if it fails (throw an exception)
though I agree with above.. exceptions should be used for exceptional/error conditions, and returning a null is best when using checks.
EAFP vs. LBYL in Python:
http://mail.python.org/pipermail/python-list/2003-May/205182.html
(Web Archive)
Exceptions are related to Design by Contract.
The interface of an objects is actually a contract between two objects, the caller must meet the contract or else the receiver may just fail with an exception. There are two possible contracts
1) all input the method is valid, in which case you must return null when the object is not found.
2) only some input is valid, ie that which results in a found object. In which case you MUST offer a second method that allows the caller to determine if its input will be correct. For example
is_present(key)
find(key) throws Exception
IF and ONLY IF you provide both methods of the 2nd contract, you are allowed to throw an exception is nothing is found!
I prefer to just return a null, and rely on the caller to handle it appropriately. The (for lack of a better word) exception is if I am absolutely 'certain' this method will return an object. In that case a failure is an exceptional should and should throw.
Depends on what it means that the object is not found.
If it's a normal state of affairs, then return null. This is just something that might happen once in an while, and the callers should check for it.
If it's an error, then throw an exception, the callers should decide what to do with the error condition of missing object.
Ultimately either would work, although most people generally consider it good practice to only use Exceptions when something, well, Exceptional has happened.
Here are a couple more suggestions.
If returning a collection, avoid returning null, return an empty collection which makes enumeration easier to deal with without a null check first.
Several .NET API's use the pattern of a thrownOnError parameter which gives the caller the choice as whether it is really an exceptional situation or not if the object is not found. Type.GetType is an example of this. Another common pattern with BCL is the TryGet pattern where a boolean is returned and the value is passed via an output parameter.
You could also consider the Null Object pattern in some circumstances which can either be a default or a version with no behaviour. The key is avoid null checks throughout the code base. See here for more information Link
In some functions I add a parameter:
..., bool verify = true)
True means throw, false means return some error return value. This way, whoever uses this function has both options. The default should be true, for the benefit of those who forget about error handling.
Return a null instead of throwing an exception and clearly document the possibility of a null return value in the API documentation. If the calling code doesn't honor the API and check for the null case, it will most probably result in some sort of "null pointer exception" anyway :)
In C++, I can think of 3 different flavors of setting up a method that finds an object.
Option A
Object *findObject(Key &key);
Return null when an object can't be found. Nice and simple. I'd go with this one. The alternative approaches below are for people who don't hate out-params.
Option B
void findObject(Key &key, Object &found);
Pass in a reference to variable that will be receiving the object. The method thrown an exception when an object can't be found. This convention is probably more suitable if it's not really expected for an object not to be found -- hence you throw an exception to signify that it's an unexpected case.
Option C
bool findObject(Key &key, Object &found);
The method returns false when an object can't be found. The advantage of this over option A is that you can check for the error case in one clear step:
if (!findObject(myKey, myObj)) { ...
referring only to the case where null is not considered an exceptional behavior i am definitely for the try method, it is clear, no need to "read the book" or "look before you leap" as was said here
so basically:
bool TryFindObject(RequestParam request, out ResponseParam response)
and this means that the user's code will also be clear
...
if(TryFindObject(request, out response)
{
handleSuccess(response)
}
else
{
handleFailure()
}
...
If it's important for client code to know the difference between found and not found and this is supposed to be a routine behavior, then it's best to return null. Client code can then decide what to do.
Generally it should return null. The code calling the method should decide whether to throw an exception or to attempt something else.
Or return an Option
An option is basically a container class that forces the client to handle booth cases. Scala has this concept, look up it's API.
Then you have methods like T getOrElse(T valueIfNull) on this object thet either return the found object, or an allternative the client specifieces.
Prefer returning null --
If the caller uses it without checking, the exception happens right there anyway.
If the caller doesn't really use it, don't tax him a try/catch block
Unfortunately JDK is inconsistent, if you trying access non existing key in resource bundle, you get not found exception and when you request value from map you get null if it doesn't exists. So I would change winner answer to the following, if found value can be null, then raise exception when it isn't found, otherwise return null. So follow to the rule with one exception, if you need to know why value isn't found then always raise exception, or..
If the method returns a collection, then return an empty collection (like sayed above). But please not Collections.EMPTY_LIST or such! (in case of Java)
If the method retrives a single object, then You have some options.
If the method should always find the result and it's a real exception case not to find the object, then you should throw an exception (in Java: please an unchecked Exception)
(Java only) If you can tolerate that the method throws a checked exception, throw a project specific ObjectNotFoundException or the like. In this case the compiler says you if you forget to handle the exception. (This is my preferred handling of not found things in Java.)
If you say it's really ok, if the object is not found and your Method name is like findBookForAuthorOrReturnNull(..), then you can return null. In this case it is strongly recomminded to use some sort of static check or compiler check, wich prevents dereferencing of the result without a null check. In case of Java it can be eg. FindBugs (see DefaultAnnotation at http://findbugs.sourceforge.net/manual/annotations.html) or IntelliJ-Checking.
Be careful, if you decide to return a null. If you are not the only programmer in project you will get NullPointerExceptions (in Java or whatever in other Languages) at run time! So don't return nulls which are not checked at compile time.
As long as it's supposed to return a reference to the object, returning a NULL should be good.
However, if it's returning the whole bloody thing (like in C++ if you do: 'return blah;' rather than 'return &blah;' (or 'blah' is a pointer), then you can't return a NULL, because it's not of type 'object'. In that case, throwing an exception, or returning a blank object that doesn't have a success flag set is how I would approach the problem.
Don't think anyone mentioned the overhead in exception handling - takes additional resources to load up and process the exception so unless its a true app killing or process stopping event (going forward would cause more harm than good) I would opt for passing back a value the calling environment could interpret as it sees fit.
I agree with what seems to be the consensus here (return null if "not found" is a normal possible outcome, or throw an exception if the semantics of the situation require that the object always be found).
There is, however, a third possibility that might make sense depending on your particular situation. Your method could return a default object of some sort in the "not found" condition, allowing calling code to be assured that it will always receive a valid object without the need for null checking or exception catching.
Return a null, exceptions are exactly that: something your code does that isn't expected.
Exceptions should be exceptional. Return null if it is valid to return a null.
If you are using a library or another class which throws an exception, you should rethrow it. Here is an example. Example2.java is like library and Example.java uses it's object. Main.java is an example to handle this Exception. You should show a meaningful message and (if needed) stack trace to the user in the calling side.
Main.java
public class Main {
public static void main(String[] args) {
Example example = new Example();
try {
Example2 obj = example.doExample();
if(obj == null){
System.out.println("Hey object is null!");
}
} catch (Exception e) {
System.out.println("Congratulations, you caught the exception!");
System.out.println("Here is stack trace:");
e.printStackTrace();
}
}
}
Example.java
/**
* Example.java
* #author Seval
* #date 10/22/2014
*/
public class Example {
/**
* Returns Example2 object
* If there is no Example2 object, throws exception
*
* #return obj Example2
* #throws Exception
*/
public Example2 doExample() throws Exception {
try {
// Get the object
Example2 obj = new Example2();
return obj;
} catch (Exception e) {
// Log the exception and rethrow
// Log.logException(e);
throw e;
}
}
}
Example2.java
/**
* Example2.java
* #author Seval
*
*/
public class Example2 {
/**
* Constructor of Example2
* #throws Exception
*/
public Example2() throws Exception{
throw new Exception("Please set the \"obj\"");
}
}
That really depends on if you expect to find the object, or not. If you follow the school of thought that exceptions should be used for indicating something, well, err, exceptional has occured then:
Object found; return object
Object not-found; throw exception
Otherwise, return null.

Categories

Resources