Reputation: 1
What is the programming implementation of NullPointerException
in java. Having a book which describe NullPointerException
,and done using first throw it using throw
statement. But how to implement this exception in simple try catch block without using throw.
like we can throw ArithmetcException
by doing throw new ArithmetricException()
or to generate the exception we do in
try {
a=b/0;
} catch(ArithmeticException x);
Like the above, how to generate NullPointerException
without explicitly throwing it?
Upvotes: 0
Views: 64
Reputation: 1
You can easily throw NullPointerException , just use this code
try{
String nullString = null;
nullString.isEmpty();
catch(NullPointerException nex){
System.out.println("NullPointerException:"+nex);
}
The exception will be thrown because you are trying to call isEmpty() method on a null object.
Upvotes: 0
Reputation: 393801
Any method call performed on any null
object reference would cause NullPointerException
.
String s = null;
s.toString();
Upvotes: 1
Reputation: 35598
If I understand correctly:
Object obj = null;
obj.equals(this);
Will cause an NullPointerException
.
Upvotes: 1