Let's say I have a SOA. Now I make a service call and I get an object which has nested objects as field. Let's say:
class A {
B b;
}
class B {
C c;
}
class C {
D d;
}
Now if I need to access a field from class D when I get object as a response from a service call i need to perform :
if(a == null || a.getB() == null || a.getB().getC() == null || a.getB().getC().getD() == null) {
throw someexception();
}
Is there a graceful way of handling the same predicate?
You can use Optional:
D d = Optional.ofNullable(a)
.map(A::getB)
.map(B::getC)
.map(C::getD)
.orElseThrow(MyNullException::new);
You can also do orElseGet(D::new) if you want to use a default value instead.
In your specific example, you're throwing an exception. That being the case, this is apparently an exceptional condition, so we can use exceptions to manage it:
D d;
try {
d = a.getB().getC().getD();
}
catch (NullPointerException npe) {
throw new SomeException(npe);
}
doYourStuffWith(d);
If you weren't throwing an exception, you wouldn't do that; you don't want to use exceptions for normal program flow. In that situation, your current check is fine, or you could use more specific exceptions with a series of if/else, or in a Java 8 context do that lovely thing Peter showed us. :-)
Have you tried something like this?
try {
//Try and do something
} catch(NullPointerException e) {
//Something was null, therefore an exception was thrown
}
Related
Is there any alternative in java to make code possible in jdk1.6. I know same is possible in jdk 1.7, but i am stuck with jdk1.6.
Below code can catch multiple exceptions and i want to handle these exception and add it to database table. Since for all 3 exceptions, my exception handling logic is going to remain same. I don't want repeat same code for multiple catch blocks.
try{
//do somthing here
}catch(CustomException1 ex1 | CustomException2 ex2 | CustomException3 ex3){
// Here goes common Exception handing logic.
}
try{
//do somthing here
}catch(Exception e){
if(e instanceof CustomException1 || e instanceof CustomException2 || e instanceof CustomException3 ) {
// Here goes common Exception handing logic.
} else { throw e;}
}
There is no other option I think.
This syntax was added in Java 1.7 because it was difficult to do it cleanly before.
There are a few things you can do:
Use a single catch for a common base class of CustomExceptionX (usually Exception, but sometimes you have to go up to Throwable if one of these is actually an Error). The drawback is that it will also catch RuntimeExceptions, so you will have to do a runtime check like Subin suggests. If you are the one defining the CustomExceptionX, you can define a common superclass for this usage and you won't have to do a runtime check.
Put your common logic in a function and call this function in both catches. This way the only duplication will be the call to the function.
It is not possible in the jdk1.6. I have just found an alternative. what you can do is define a class level variable.
Object c ;
then in your corresponding catch block assign the reference.
catch(CustomException1 cx1) {
c= cx1;
}
catch(CustomException2 cx2){
c = cx2;
}
if( c instanceof cx1 || c instanceof cx2)
// put your common logic here
i hope it will solve your problem.
I finally went ahead with this code,
try{
//do somthing here
}catch(SuperExceptionClass ex){
if (ex instanceof CustomException1 || ex instanceof CustomException2 || ex instanceof CustomException2) {
// Here goes common Exception handing logic.
} else {
throw ex;
}
}
In code we have got a lot of chain methods, for example obj.getA().getB().getC().getD(). I want to create helper class which will check if method getD() isn't null, but before that I need to check all previous getters. I can do it in this way:
try {
obj.getA().getB().getC().getD();
}
catch (NullPointerException e) {
// some getter is null
}
or (which is "silly")
if (obj!null && obj.getA()!=null && obj.getA().getB()!=null && ...) {
obj.getA().getB().getC().getD();
}
else {
// some getter is null
}
I don't want to check it every time using try{} catch() in my code. What is the best solution for this purpose?
I think that the best will be:
obj.getA().getB().getC().getD().isNull() - for this purpose I will need to change all of my getters, for example implement some interface which contains isNull() method.
NullObjectHelper.isNull(obj.getA().getB().getC().getD()); - this will be the best (I think so) but how to implement this?
As of Java 8 you can use methods like Optional.isPresent and Optional.orElse to handle null in getter chains:
boolean dNotNull = Optional.ofNullable(obj)
.map(Obj::getA)
.map(A::getB)
.map(B::getC)
.map(C::getD)
.isPresent();
While this is preferable to catching NullPointerException the downside of this approach is the object allocations for Optional instances.
It is possible to write your own static methods that perform similar operations without this overhead:
boolean dNotNull = Nulls.isNotNull(obj, Obj::getA, A::getB, B::getC, C::getD);
For a sample implementation, see the Nullifier type here.
No approach is likely to have greater runtime efficiency than nested if-not-null checks.
You can achieve the desired result with Option pattern. This enforces you to change a method signature, but basically if your method returns some type T, it guarantees it has some non-null value, and if it returnsOption<T> it means it either has value T, or null.
Java 7 had some feature called null safety, but it was removed from the final release. You could do:
obj?.getA()?.getB()?.getC()?.getD()
Moreover, Java 8 will add a feature called Optional so you would do it safely.
In fact, if you really want to use that now, try Null Object pattern. It means that instead of returning plain null you can return some sort of default value, which won't trigger NullPointerException. Though, you need add some changes to your getters
class Object {
A getA() {
// ...
return a == null ? A.NULL : a;
}
}
class A {
static A NULL = new A(); // some default behaviour
B getB() {
if (this == NULL) return B.NULL;
// ...
return b == null ? B.NULL : b;
}
}
EDIT: If you want utility to do it you can wrap it in some functional interface and then call it.
static boolean isNullResult(Callable call) throws Exception {
try {
return call.call() == null;
} catch (NullPointerException npe) {
return true;
}
}
Usage will be the following:
isNullResult(new Callable<Integer>() {
#Override
public Integer call() throws Exception {
return new A().getB().getC().getInt();
}
});
It won't require you to change existing functionality
As already stated, the true solution is refactoring.
In the meantime, you could just wrap your first workaround in a function:
static D getD(MyClass obj) {
try {
return obj.getA().getB().getC().getD();
}
catch (NullPointerException e) {
return null; // Or even better, some default D
}
}
At the caller site:
D d = getD(obj);
At least you don't have to trash the caller with try-catch blocks. You still need to handle the errors somehow, when some of the intermediate getX() call returns a null and so d becomes null. The best would be to return some default D in the wrapper function.
I don't see how the two options you list at the end of your question would help if any of the intermediate getX() returns a null; you will get a NullPointerException.
Consider the following Code Snippet:
if (foo != null
&& foo.bar != null
&& foo.bar.boo != null
&& foo.bar.boo.far != null)
{
doSomething (foo.bar.boo.far);
}
My question is simple: is there a more simple\shorter way to do this ?
In detail: is there a more simple way to validate each part of the chain, I'd imagine similar to this ..
if (validate("foo.bar.boo.far"))
{
doSomething (foo.bar.boo.far);
}
Maybe like that ?
if (FooUtils.isFarNotEmpty(foo)){
doSomething (foo.bar.boo.far);
}
and in FooUtils :
boolean isFarNotEmpty (Foo foo){
return foo != null &&
foo.bar != null &&
foo.bar.boo != null &&
foo.bar.boo.far != null;
}
In my opinion this expression is perfect, nothing can be simpler
why you are using public instance variable, encapsulate your public variables and create getter and setter for them and you can perform these check in your getter, and you can return new Object() if any of them is null, or you can run this statement in try-catch block but not recommended,
If this is your API please consider some advice.
"I call it my billion-dollar mistake." - Sir C. A. R. Hoare, on his
invention of the null reference
There's not much you can do with this, unfortunately. If you ask me, it's a problem with the Java language. Groovy has something called the Safe Navigation Operator ?. that is specifically for this purpose. Here are two things I've done in the past.
The answer that Grisha already gave, so I won't repeat it
Naively wrote code that accesses it, and surround it in a try/catch for a NPE. Here's an example:
try {
if (foo.bar.boo.far != null) {
//do something
}
} catch (NullPointerException e) {
//do what you would do in an else
}
I don't particularly like the 2nd option, but I say if it actually makes the code cleaner, consider using it.
One time I was working with a library that is a very thin wrapper over an XML schema and I decided to use the 2nd option for this case. If I didn't, the code would have been harder to maintain because it would be so easy to forget a null check and they cluttered up the important logic. I think that's a valid case for using it.
Please try this code
try {
if (foo.bar.boo.far != null) {
//No object is null
}
} catch (Exception e) {
// some object is null and causes null point exception.
}
If I have a set method in which I want to modify some values,
if an user enter wrong values which is the best exception to throw to indicate that failure?
public void setSomething(int d) throws ....
{
if (d < 10 && d >= 0)
{
// ok do something
}
else throw new ... // throw some exception
}
I'd go for IllegalArgumentException.
Thrown to indicate that a method has been passed an illegal or
inappropriate argument.
EDIT
Another note:
Instead of
if (conditionIsTrue) {
doThis();
doThat();
} else {
throw new IllegalArgumentException();
}
write:
if (conditionNotTrue) {
throw new IllegalArgumentException();
}
doThis();
doThat();
(Though this advice may be controversial ;-)).
I agree with #Code Monkey about creating your own InvalidArgumentException, but his implementation doesn't show all the advantages it provides.
1) You can add convenience methods to simplify argument checking. For example:
InvalidArgumentException.throwIfNullOrBlank(someString, "someString");
vs.
if (someString == null || someString.trim().isEmpty()) {
throw new IllegalArgumentException("someString is null or blank");
}
2) You can write unit tests that confirm which argument was invalid. If you throw IllegalArgumentException, your unit test can't confirm that it was thrown for the reason you expect it to be thrown. You can't even tell that it was thrown by your own code.
try {
someClass.someMethod(someValue);
Assert.fail("Should have thrown an InvalidArgumentException");
} catch (InvalidArgumentException e) {
Assert.assertEquals("someValue", e.getArgumentName());
}
3) You can tell that the exception was thrown from within your own code. (This is a minor point that doesn't have much practical advantage)
If the number is an index, you could use IndexOutOfBoundsException. Otherwise, as Oliver says, IllegalArgumentException.
Don't be afraid to create a subclass of IllegalArgumentException to be more precise about the problem. Any catch blocks written for IllegalArgumentException will still catch it, but the stack trace will be slightly more informative.
Is there a sense to handle null pointer exception by such way like
private void doWork(Object object) {
if (object == null) {
try {
throw new IllegalArgumentException();
} catch (Exception e) {
e.printStackTrace();
}
} else {
...
}
}
No, that doesn't really make sense.
Don't catch the exception. Just do
if (object == null)
throw new IllegalArgumentException("Argument object may not equal null");
According to your suggestion the method would be document as
Do some work given argument object. If object is null it prints some garbage on standard out and does nothing else.
As a side-note, since you're still learning Java, your try-catch block:
try {
throw new IllegalArgumentException();
} catch (Exception e) {
e.printStackTrace();
}
... is equivalent to ...
new IllegalArgumentException().printStackTrace();
It's fine to throw an exception if a null is an exceptional state, but the try/catch does not make much sense: you throw a new IllegalArgumentException();, catch it right afterwards, print a stacktrace an continue.
If you can handle the null case and just want to report, then you should write it to a log file:
if (object == null) {
log.warn("method doWork has been called with a null argument");
}
// continue in the method
Otherwise the method should throw the exception back at it's caller
if (object == null) {
throw new IllegalArgumentException("Hey stupid, RTFJD, NO calls with null!");
}
(replace exception message with something meaningful ;) )
First, that code could be written more simply as:
private void doWork(Object object) {
if (object == null) {
new IllegalArgumentException().printStackTrace();
} else {
}
}
or (almost equivalently) as
private void doWork(Object object) {
if (object == null) {
Thread.dumpStack();
} else {
}
}
Second, is it doing something useful? Yes, it is printing is a stack trace for the current thread.
Third, is it a good idea? IMO, definitely NOT.
It is sending stuff to the standard error, which may be going to the console (where it could be lost if nobody is watching) or to /dev/null. Errors should be logged properly using your preferred logging subsystem.
It looks like it is squashing a probable error condition (i.e. the program is broken because this method has been called with an illegal argument) and then continuing. If this is really an error condition, then the code should probably be bailing out. If it is not, then the stack trace is noise.
In short, this looks like a "bandaid" solution to some problem. The correct solution is to remove this code (or replace it with code that simply throws IllegalArgumentException), and when the exception occurs figure out where it is coming from and fix the root problem.
Alternative:
private void throwIfNull(Object object, String message) throws NullPointerException {
if (object == null) {
throw new NullPointerException(message);
}
}
Then you can specify your method to throw the exception back to the caller, like so
private void doWork(Object object) throws Exception {
throwIfNull(object, "Object is null");
//Other work....
doWorkInternal(object);
}
In this case, you know that if doWorkInternal() method is called, the object was never null.
The simplest way is
if (object != null) {
doWork();
} else {
}
if you don't want to catch the exception inside your function and let some calling function to handle this,
its better to do this :
public void doWork(Object object) throws NullPointerException {
//code that might result NullPointerException.
//no handling of exception by yourself
}
But if want/should handle the exception within the definition of your method,
your code is good.
When object came as null, it will automatically throw an null pointer exception. but you didn't handle it, and you are trying to throw an "IllegalArgumentException()", which isn't possible.
if (object == null)
this line itself, an exception is thrown, and it won't execute the rest of the line.