Catching nullpointerexception in Java [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I tried using try-catch block to catch NullPointerException but still the following program is giving errors. Am I doing something wrong or is there any other way to catch NullPointerException in the following program. Any help is highly appreciated.
public class Circular_or_not
{
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
try
{
LinkedListNode[] nodes = new LinkedListNode[10];
for (int i = 0; i < 10; i++)
{
nodes[i] = new LinkedListNode(i, null, i > 0 ? nodes[i - 1] : null);
}
// Create loop;
// nodes[9].next = nodes[3];
Boolean abc= Check_Circular(nodes[0]);
System.out.print(abc);
}
catch(NullPointerException e)
{
System.out.print("NullPointerException caught");
}
}
public static boolean Check_Circular(LinkedListNode head)
{
LinkedListNode n1 = head;
LinkedListNode n2 = head;
// Find meeting point
while (n2.next != null)
{
n1 = n1.next;
n2 = n2.next.next;
if (n1 == n2)
{
return true;
}
}
return false;
}
}

NullPointerException is a run-time exception which is not recommended to catch it, but instead avoid it:
if(someVariable != null) someVariable.doSomething();
else
{
// do something else
}

As stated already within another answer it is not recommended to catch a NullPointerException. However you definitely could catch it, like the following example shows.
public class Testclass{
public static void main(String[] args) {
try {
doSomething();
} catch (NullPointerException e) {
System.out.print("Caught the NullPointerException");
}
}
public static void doSomething() {
String nullString = null;
nullString.endsWith("test");
}
}
Although a NPE can be caught you definitely shouldn't do that but fix the initial issue, which is the Check_Circular method.

The problem with your code is in your loop in Check_Circular. You are advancing through the list using n1 by going one node at a time. By reassigning n2 to n2.next.next you are advancing through it two at a time.
When you do that, n2.next.next may be null, so n2 will be null after the assignment. When the loop repeats and it checks if n2.next is not null, it throws the NPE because it can't get to next since n2 is already null.
You want to do something like what Alex posted instead.

I think your problem is inside CheckCircular, in the while condition:
Assume you have 2 nodes, first N1 and N2 point to the same node, then N1 points to the second node (last) and N2 points to null (because it's N2.next.next). In the next loop, you try to call the 'next' method on N2, but N2 is null. There you have it, NullPointerException

You should be catching NullPointerException with the code above, but that doesn't change the fact that your Check_Circular is wrong. If you fix Check_Circular, your code won't throw NullPointerException in the first place, and work as intended.
Try:
public static boolean Check_Circular(LinkedListNode head)
{
LinkedListNode curNode = head;
do
{
curNode = curNode.next;
if(curNode == head)
return true;
}
while(curNode != null);
return false;
}

Related

Throw exception instead of return in Java method

I'm writing Deque class on Java, according to Algorithms, Part 1 on Coursera. And currently my array-based Deque has method removeLast():
public Item removeLast() {
if (size() == array.length / 4) {
resize(array.length / 2);
}
if (head != tail) {
Item tmp = array[--head];
array[head] = null;
return tmp;
}
throw new NoSuchElementException("Stack underflow");
}
If head == tail means Deque is empty and I throw exception, according to homework specification, at the end of method instead of return statement. This code gives direct intention about invariants (head != tail).
On the other hand method may be rewritten like this:
public Item removeLastRewritten() {
if (size() == array.length / 4) {
resize(array.length / 2);
}
if (head == tail) {
throw new NoSuchElementException("Stack underflow");
}
Item tmp = array[--head];
array[head] = null;
return tmp;
}
In my opinion removeLast is more clearly written by these reasons:
Adhere to pessimistic scenario - always fail, only if ... which is more reliable approach, especially when method code will enlarge and become more complicated.
Gives more clear link between invariant tail != head and subsequent if {} code block.
I have the following questions:
Which is a better approach?
Is it considered an appropriate/good practice to write like removeLast?
What is considered a best practice for Java? Is there any code style about it (I couldn't find any)?
There is not a wrong answer. In GrepCode you can find every flavour you propose:
Inside a if with the != operator and at the end of the method:
E java.util.PriorityQueue.next()
public E More ...next() {
if (... != ...)
throw new ConcurrentModificationException();
...
if (...) {
return lastRetElt;
}
throw new NoSuchElementException();
}
Inside a if with the == operator
E org.fluentlenium.core.domain.FluentList.first()
public E More ...first() {
if (this.size() == 0) {
throw new NoSuchElementException("Element not found");
}
return this.get(0);
}
The reason why it looks weird is because you omit the else block of your if block, which would incorporate either leftover that comes after the if block in both your methods. The reason you can get away with it here is because the thrown exception will disrupt the flow of your method.
I think it's better not to rely on that and just be nice and use the if-else blocks intuitively.
public Item removeLastRewrittenAgain() {
if (size() == array.length / 4) {
resize(array.length / 2);
}
if (head != tail) { // invert the if-else block if preferred, it would not make any difference
Item tmp = array[--head];
array[head] = null;
return tmp;
} else {
throw new NoSuchElementException("Stack underflow");
}
}
Another reason why I don't really like to throw exceptions before the end of a method is that I strongly believe in and thus thoroughly use the concept of a single point of exit, meaning I don't leave the method somewhere in the middle which I believe is more difficult to read for someone not familiar with the code.
One place to return your value (or thrown exceptions): the very bottom of your method.
Your code becomes more readable if you explicitly mention the else, regardless of your choice.
Then there is the dilemma of
if (head != tail) {
Item tmp = array[--head];
array[head] = null;
return tmp;
} else {
throw new NoSuchElementException("Stack underflow");
}
versus
if (head == tail) {
throw new NoSuchElementException("Stack underflow");
} else {
Item tmp = array[--head];
array[head] = null;
return tmp;
}
Here I strongly prefer the second one. When I'm reading the "complicated part" of the if statement, I want to know why I'm actually inside an if. When reading the first variant the whole reason for the if only becomes apparent when you're throwing the exception.
I guess you could also solve that by writing
boolean isEmpty = head == tail;
if (!isEmpty) {
Item tmp = array[--head];
array[head] = null;
return tmp;
}
throw new NoSuchElementException("Stack underflow");
but I prefer the version that throws the exception as soon as you know something is wrong.

Try-Catch block termination

I'm using a try-catch block to catch any exceptions that might be thrown when I run certain methods on a stack. My code for the pop method looks like this:
public T pop()
{
T temp = null;
try
{
temp = first.data;
}
catch(Exception e)
{
System.out.println("Invalid operation on an empty stack");
}
first = first.next;
return temp;
}
When I run the program the exception is caught... my terminal produces this:
(menu choice 'd' is the pop method)
Please enter a menu choice: d
Invalid operation on an empty stack
Exception in thread "main" java.lang.NullPointerException
at MyStack.pop(MyStack.java:58)
at StackTest.main(StackTest.java:52)
so I think my exception is being caught since it prints "Invalid operation...", but my program also terminates when the exception is thrown. Any help?
We have learned a very valuable lesson today: don't catch Exception without good reason.
The problem here is that first is coming back null, so we're going to throw that exception once we try to dereference it.
Let's look at it from a different angle. If first is null, we know we can't pop anything, so we should be throwing the exception instead.
public T pop() {
if(first == null) {
throw new EmptyStackException("Invalid operation on empty stack");
}
T value = first.data;
first = first.next;
return value;
}
Seems like there's another exception being thrown, after your catch block. It is very likely that first is null. That causes the catch block to be executed (because first.data is a null pointer exception), but it also causes another null pointer exception at
first = first.next;
Thus you have an uncaught exception. How you tackle this is up to you; it's more of a design decision than a correctness one.
The simplest and probably correct option is to do all of your modification inside the try block, so if something goes wrong you don't resume operations that probably won't work.
public T pop(){
T temp = null;
try{
temp = first.data;
first = first.next;
}
catch(Exception e){
System.out.println("Invalid operation on an empty stack");
}
return temp;
}
Of course, the try..catch construction isn't really appropriate here. A much more succinct way to write the same method would be:
public T pop(){
if(first == null) return null;
//By virtue of reaching this point, first is necessarily non-null.
T temp = first.data;
first = first.next;
return temp;
}
But if the goal was to experiment with try..catch use my top answer.
first is clearly null based on your output. Now, you're catching the NullPointerException that arises from temp = first.data, but not the one that arises from first = first.next (since that assignment is not enclosed with a try block):
public T pop()
{
T temp = null;
try
{
temp = first.data; // <-- you catch the exception thrown here
}
catch(Exception e)
{
System.out.println("Invalid operation on an empty stack");
}
first = first.next; // <-- but you don't catch the one thrown here
return temp;
}
In general it's a very bad idea to catch a NullPointerException; explicitly check for null beforehand.
It's highly likely that your first is null.
Try this code instead
public T pop()
{
T temp = null;
try
{
if (first != null)
{
temp = first.data;
first = first.next;
}
}
catch(Exception e)
{
System.out.println("Invalid operation on an empty stack");
}
return temp;
}

null pointer exception from my code from the while loop

I decleared free block like
private DoublyLinkedList freeblock = new DoublyLinkedList();
and I initialize the freeblock in the constructor.
freeblock.add(new DoublyLinkedList.Node(null, null, 0, initBlockSize));
inside of one of method of my class, (below is part of my method.)
I get null pointer exception. I think the while loop has a problem. Can anyone help me to solve this problem?
symptom: java.lang.NullPointerException
at LinearMemPool.enlarge(LinearMemPool.java:220)
private void enlarge(int addSize) {
DoublyLinkedList.Node node = freeblock.head;
while (node.next != null) {
node = node.next;
}
}
Evidently freeblock.head is null. Look what add does.
Your enlarge method seems a bit dangerous. Try changing the null check to:
private void enlarge(int addSize) {
DoublyLinkedList.Node node = freeblock.head;
while (node != null) {
node = node.next;
}
}
As for the reason why your head is null, I'd debug the freeblock.add(...) method.
First check to see freeblock.head is null because most likely it is:
if(node!=null){
while(node.next!=null){
....
}
else{
System.out.println("Freeblock is null but why.....");
}
You probably should do this normally if the freeblock.head can ever be null. And just for cleaning up purposes:
void newMethod(Node node, int size){
if(node!=null)
enlarge(size);
else{
System.out.println("Freeblock is null");
}
}

Return Objects from Arraylist

My problem is, that I want to return an Object from the ArrayList "blocks".
My code doesn't work - error says This method must return a result of type block
public block getBlockUnderneath (int x, int y){
for(int i = 0; i<blocks.size(); i++){
if (blocks.get(i).x == x) {
return blocks.get(i);
}
}
}
You have two issues:
If blocks.size()==0 your method returns nothing
If none of the blocks in blocks have block.x==x your method returns nothing.
In Java a method must return a value of it is declared to do so.
The easiest solution to your issue is to return null at the end of the method:
public block getBlockUnderneath (int x, int y){
for(final block b : blocks){
if (b.x == x) {
return b;
}
}
return null;
}
Notice this uses an enhanced-for-loop, this is the recommended way to loop over Collections (or anything that implements Iterable<T>) in Java.
A better approach might be to throw an exception if no item is found:
public block getBlockUnderneath (int x, int y){
for(final block b : blocks){
if (b.x == x) {
return b;
}
}
throw new NoSuchElementException();
}
In either case you would need to handle the corner case in code that calls this method.
P.S. please stick to Java naming conventions. Classes should be in PascalCase - so you block class should be called Block.
Just for fun, in Java 8:
public block getBlockUnderneath(int x, int y) {
return blocks.stream().filter((b) -> b.x == x).findFirst().get();
}
The problem with your method is that there exists a scenario in which the return block is not executed. In that case, when a method is not declared to be void, you must declare the exit point for it.
You can exit using return or throw an exception. The choice depends on what your program should do if the requested value could not be found.
public block getBlockUnderneath (int x, int y){
for(int i = 0; i<blocks.size(); i++){
if (blocks.get(i).x == x) {
return blocks.get(i);
}
}
return null; //or throw NoSuchElementException or IllegalStateException
}
What's more you can improve you code by using a for-each loop. This solution may give you better performance and also code security as it uses an iterator rather than accessing item by index which is not necessarily efficient.
In this case you access the same item twice.
if (blocks.get(i).x == x) {
return blocks.get(i);
}
Full example
public Block findBlock(int x} { //The class name is Block
for(Block block : blocks) {
if(block.x == x {
return block;
}
}
return null;
}
Be also aware of that returning null may cause problems and thus is considered bad practice. You can avoid null, thanks to checked exceptions, default values or using Null object
There is a native implementation of this common coding pattern in Java 8. Using the Optional<T> class from the Guava library can solve this problem for versions of Java < 8.
public Optional<Block> findBlock(int x} { //The class name is Block
for(Block block : blocks) {
if(block.x == x {
return Optional.of(block);
}
}
return Optional.empty();
}
Usage
public void someActionWithBlocK() {
Optional<Block> block = findBlock(5);
if(block.isPresent()) {
//some action with block
}
}
You could never loop.
If you have a return statement inside of a loop, then the compiler doesn't take the bonafide guarantee that the loop will execute and that you will return. To get around that, you must also return after your loop.
Or, better yet, have one variable to return, like such:
block ret = null;
for(block b : blocks) {
if(b.x == x) { // I'm going to go over this in a mo
ret = b;
break;
}
}
return ret;

Eclipse marks lines as dead code

I have this function with some dead code, marked by Eclipse.
I have two lines that check a & b. Lines that check b are marked as null.
public int[] runThis(List<Integer> buildIds, List<Integer> scenarios, boolean oflag) {
int rating[] = new int[scenarios.size()];
if(buildIds == null) {
System.out.println("ERROR - Building ID list is null!");
return null;
}
if(scenarios == null) {
System.out.println("ERROR - Scenario list is null!"); //dead
return null; //dead
}
return rating;
}
Why does Ellipse make the two lines as dead? Any help? Thanks very much for your time.
Because you've already called scenarios.size() in your array constructor. This guarantees scenarios isn't null or it will have thrown an exception by that point.

Categories

Resources