0

I have QStorage class that stores the Queue contents.

class QStorage{
   Queue<A> q = new PriorityQueue<A>(5);

  public Queue<a> readQ(){
   try{
   FileInputStream fin = new FileInputStream("/home/requestQ.ser");
   ObjectInputStream ois = new ObjectInputStream(fin);
   q = (Queue)ois.readObject();
   }catch(Exception e){}

   return q;
  }
}

And in another class I am calling readQ() method of above class to store the queue content of the file to some another queue.

class MyQ{
  public static void main(String args[]){
    QueueStorage qs = new QueueStorage(); 
    Queue<A> myQ = new PriorityQueue<A>(5);
    myQ = qs.readQ();
    //...some other stuffs goes here 
 }
}

Here if already some entries of the queue are stored in file, readQ() correctly returns those entries. But if there are no entries stored in file(i mean the empty queue is stored) then this method gives nullPointerException and my program stops working.

Note: I have the requirement that I should check the stored contents without knowing if it is empty or not.

Please help. Thanks.

Winn
  • 413
  • 2
  • 6
  • 17

1 Answers1

0

The NPE is caused by your appalling practice of ignoring the EOFException that is thrown if the file is empty, and indeed all IOExceptions, ClassNotFoundExceptions, RuntimeExceptions, etc etc etc. Don't do that. Either:

  1. Have the readQ() method declared to throw IOException etc, and put the call to it in a try/catch block, or
  2. Have it catch its own exceptions as now, return null on exception as now (not forgetting g to log the exception so you know what is happening), but test for null after calling it.

At present you are just blindly assuming the method will succeed. It won't.

NB If the file is empty, it doesn't mean 'the empty queue is stored'. It means you had a catastrophic failure writing anything to the file, which you doubtless also ignored according to your practice as exhibited here.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Oh..I forgot to `return null` on Exception. Thanks a lot @EJP for your suggestions. Its working now. – Winn Oct 25 '13 at 03:41