Java prevent from returning null - java

I'm pretty new to Java so bear with me. Basically I have a class named "returnPages" that returns the parent page that you are currently on. The problem is when you're at the highest level or the root it throws an error, logically because the root doesn't have a parent it will throw a null pointer exception. How would I prevent an error being thrown when your at the root? I thought the below code would work but I'm simply getting a null pointer exception were I start my conditional. Note: I'm trying to run this in the JSP, modifying the returnPages class will result in multiple conflicts across the site. Also the returnPages class takes two arguments the first is parent page followed by the current page your on.
Page rootPage = properties.get("rootPage", "");
if(returnPages.getPath(rootPage, currentPage) != null){
List<Page> trail = returnPages.getPath(rootPage, currentPage);
} else {
//show something here
}
Any help is greatly appreciated!

You can use
return Collections.emptyList<Page>();
Or simply
return new LinkedList<Page>();
The first option returns an immutable list, so attempting to add anything to that list will fail with an exception. You use less memory though and ensure the list is not modified, which is sometimes a good thing.
Edit: why are you doing the lookup twice?
List<Page> trail = returnPages.getPath(rootPage, currentPage);
if (trail == null) {
trail = Collections.emptyList<Page>();
}

If returnPages.getPath(rootPage, currentPage) is throwing an NPE yo uhave to deal with it. you cannot check if it returns null or not
try {
List<Page> trail = returnPages.getPath(rootPage, currentPage);
} catch (NullPointerException e){
//show something here
}
There are great debates about unchecked and checked exceptions in java. NullPointer is an unchecked exception so usually means programmer error. Some people say you should not catch them. What you could do instead of returning null is return an empty list
Edit after comment:
A null pointer is thrown when you try and access something on a null object. (It's really a NullReferenceException but again there are many debates on that)
What you are doing is checking if the returned object from the method is null. Inside the returnPages.getPath(rootPage, currentPage) it is throwing a NullPointerException - not returning it. (in effect returning nothing because of this error condition and throwing the exception). When to throw an exception? gives details on this. In older languages error codes are returned so you could do a check like you are. Java has an exception handling framework which is why the author of getPath has decided to throw an exception rather than return null

You should paste the stacktrace of that NullPointerException because it is not the same thing if that exception comes from getPath() or if it comes from the condition if (returnPages.getPath(....
This might be the same issue as in your earlier question.
UPDATE: (Moving my comment to this answer.)
This is an old issue (see the question). The sentence "modifying the returnPages class will result in multiple conflicts across the site" doesn't make sense at all since neither the method interface nor its functionality has changed.

Related

Handling Null Pointer Exceptions [duplicate]

This question already has answers here:
Gracefully avoiding NullPointerException in Java
(9 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
So working through a few Java based web applications, I realized one common thing in pretty much most of the web applications. Most of them tend to run fine until you meet face to face with a Null Pointer Exception. Below is one of the methods that is returning an error:
public Map getWebSiteObjects(String path, LightWeightNode root, Integer versionId, Site site) {
Map webSiteObjects = new HashMap();
// refresh site
site = (Site)getObject(Site.class, site.getId());
webSiteObjects.put("site", site); ...... /* Dont worry about the rest */
Scenario: This method generates a tree on my application, however, it's giving a null pointer exception at runtime:
2014-10-09 12:00:18,674 ERROR org.springframework.web.servlet.DispatcherServlet - Could not complete request
java.lang.NullPointerException at com.bsdeurope.xmlcms.service.impl.TreeManagerImpl.getWebSiteObjects(TreeManagerImpl.java:159)
Now I'm quite new with some Java principals(fundamentals) and my idea to solve this was to initialize the 4 variables passed in the method therefore have:
path = null;
root =null;
versionId = null;
site = null;
before any instructions within the getWebSiteObjects method. Now I know this might not be the only solution but my question is:
1) What is good practice in terms of preventing Java Null Pointer Exceptions?
2) If there is a procedure how would you go about doing it?
Usually when working with a lot of classes especially applications with code that is badly written you end up hitting your head against the wall when you get tons of null pointer exceptions left, right and center.
There are two schools of thought on this.
One school, says test for the null and do something to "make good". For example, replace it with something else, ignore it, write a log message, and so on.
The other school is that an unexpected null is a BUG, and the correct thing to do is to allow the NullPointerException to be thrown. Then you allow the NPE to propagate up and (ideally) cause the program to crash ... or better still, fail gracefully after logging the NPE stacktrace in the application's log files.
Then it is up to the programmer to use the information in the stacktrace (and "those little grey cells" to quote a well-known fictional Belgian detective) to figure out where the unexpected null came from, and fix the root cause of the problem. Typically this entails finding the field or array element or whatever that was incorrectly initialized, of the get call that returns a null to indicate (soft) failure, or whatever. This fix may involve testing for null, or it may involve initializing something, or passing something, or correcting some logic, or adding the null test earlier in the program.
IMO, the practice of adding defensive tests for null all over the place is a bad idea. It tends to replace one kind of bug (an NPE) with another kind that is often harder to track down.
So my answers would be:
1) What is good practice in terms of preventing Java Null Pointer Exceptions?
Good practice is to not avoid the NPEs. Instead let them happen, and find / fix what is introducing the spurious null values.
2) If there is a procedure how would you go about doing it?
No there isn't. Certainly there is no procedure that >>I<< would use.
The only thing I would do would be to try to make my code throw the NPE earlier, so that the null doesn't get passed a long way from its original source. (That tends to make it easier to find and fix the root cause of the problem.)
A null check is usually enough.
// refresh site
if(site!=null){
site = (Site)getObject(Site.class, site.getId());
webSiteObjects.put("site", site); ...... /* Dont worry about the rest */
}else{
// Print an error message, or do the error handling here...
}
Note that, NullPointerException will only come when your expression evaluates to null.someFunction() . In this example, site.getId(). So null check for only site!=null is enough. If you have more object.someFunction() then you may want to do something like
if(obj1!=null && obj2!=null){
// Safe to call
obj1.function();
obj2.function();
}
For you Program here is a simple null check:
public Map getWebSiteObjects(String path, LightWeightNode root, Integer versionId, Site site) {
Map webSiteObjects = new HashMap();
if(null!=Site){
// refresh site
site = (Site)getObject(Site.class, site.getId());
webSiteObjects.put("site", site); ...... /* Dont worry about the rest */
}
//Similarly while using other arguments do similar null check
(if null!=path){
/*
Your code here...
*/
}
}
For best practices to avoid NPE check this link: NPE practices
you can put all your business logic of any method in try block
try{
Map webSiteObjects = new HashMap();
// refresh site
site = (Site)getObject(Site.class, site.getId());
webSiteObjects.put("site", site); ...... /* Dont worry about the rest */
}catch(NullPointerException e){
// error occured
e.printStackTrace();
}

Alternatives to catching NullPointerException

I recently got to know that using try and catch blocks for NullPointerExceptions is a bad practice.
If so, then I have following questions:
Why is this a bad practice?
What are the alternatives to catching a NullPointerException?
When you add a try/catch block around a section of code which you expect to throw a NPE under specific circumstances, you might inadvertently forget about another object used by that code which might also be null and cause one. When you then add the code to react on the expected NPE in the catch block, the code will also be executed on the unexpected NPE. This will output a misleading error message at best and result in completely unexpected program behavior at worst.
An example:
try {
ThingamabobFactory.getInstance().createThingamabob(ThingamabobFactory.getDefaults()).thingamabobify();
} catch(NullPointerException e) {
// so... which of the above method calls did return null?
// ...or was the NPE even thrown INSIDE one of these methods??
}
So when you expect that an object will be null in some situations and you want to handle this case, do so by checking if (object == null) to avoid any false-positives.
The big problem with catching NullPointerException is knowing what to do about it, because it can have so many possible causes.
You can be more sure you know what was null and why if you specifically test for null. For example, suppose a block of code contains a call to a method that returns null under specified circumstances, and you want to take some action if it does so. If you test the method result immediately, you know the null is due to the circumstances that cause the method to return null.
On the other hand, if you wrap the block in a try-catch and catch the NullPointerException, maybe the method returned null, but you cannot be sure that is what happened. Something else may have gone wrong in the try block, causing the exception.
You should avoid having any exceptions if possible since producing them and sending them through app is expensive in resources.
null point is easy to handle , just check to see if something is null or not
You can avoid to treated directly by using throws, or you can try an alternative method by using BCEL.
either wrapped illegal argument exception when you are at transliterate service side , or just handled predictable null case to work on preconditions of a model or method, or catch exception , inside this catch, if instance Of ... to write log or more.
generally, never directly catch null point exception, it is run time exception, it has logic:
if you know where will be null in your code , then handle it. if you don't know, the, after you catch , what you do? you are not JVM , right?

How to fix the Findbugs issue "Null value is guaranteed to be dereferenced" NP_GUARANTEED_DEREF

Hi I have got some code that is reported as having the NP_GUARANTEED_DEREF issue by Findbugs.
Now looking at my code I don't quite understand what is wrong with it, can anyone suggest what the problem is.
public void test() {
String var = "";
int index = 2;
if (index == -1) {
var = String.class.getName();
if (var.length() == 0) {
var = null;
}
} else {
var = Integer.class.getName();
if (var.length() == 0) {
var = null;
}
}
if (var == null) {// FINBUGS reports on this line NP_GUARANTEED_DEREF
/*
* There is a statement or branch that if executed guarantees that a value
* is null at this point, and that value that is guaranteed to be
* dereferenced (except on forward paths involving runtime exceptions).
*/
throw new NullPointerException("NULL");
}
}
Now drilling into the Error in Findbugs it highlights the two assignments to var = null; as cause for the bug but I don't quite understand why. It is not like I am actually doing anything with the var object I am just doing a Null check. The example is taken from real production code but stripped of anything that wasn't needed to reproduce the error. What I am wondering if this is a false positive or not. And if not what would be an appropriate fix.
Here is the link to the Findbugs Bug Detail: http://findbugs.sourceforge.net/bugDescriptions.html#NP_GUARANTEED_DEREF
[UPDATE] After recieving some feedback on this issue I have now logged this as a False Positive in the Findbugs Bugtracker on Sourceforge the link is https://sourceforge.net/tracker/?func=detail&aid=3277814&group_id=96405&atid=614693
Conversation about the problem will continue there.
I see. I can confirm the same FB behavior on my computer. Looks strange indeed. What's funny, that if you replaced throw new NullPointerException with throw new RuntimeException the bug marker would disappear.
Now I think I understand what they've meant. The wording of the message is not exact, but they are warning you against a NPE. I guess they consider explicitly throwing NPE a bad practice.
It is a bug in FindBugs, post this issue on their issue tracker page. findbugs.sf.net
OK, what FindBugs is looking for is a statement or branch that is guaranteed to lead to a null pointer exception. Originally, we only looked for dereferences of null values. We later augmented the analysis to treat
if (x == null) throw new NullPointerException()
the same as an explicit dereference of x. This was primarily to help interprocedural analysis, so that methods that had explicit null checks for their parameters would treated the same as methods that dereference their parameters without explicit null checks, and report errors when null values are passed for such parameters.
So some of the text in our error msgs might need to be updated, but we really haven't found many realistic cases where it causes confusion.
I'm not quite sure what the purpose of the above code is. At the points where are you assigning null to var, you are creating a situation that will lead to an explicit throw of a null pointer exception further down. Is that really the behavior you want?
Looking closer into the definition of the error message here, it says:
There is a statement or branch that if
executed guarantees that a value is
null at this point, and that value
that is guaranteed to be dereferenced
(except on forward paths involving
runtime exceptions)
Which makes me think it is either just letting you know var is going to be null or something actually is making findbugs think that var is referenced inside the if statement.
The code you posted looks fine, I would double check that var is not accessed in the true code.
The only thing I might change is to write the comparision backwards like so:
if (null == var)
That way it is obvious if you leave out one of the ='s/

Best practise in catching and throwing nullpointerexception?

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.

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