Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Serialization  RSS feed

 
Amey Rane
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please see the following code snippet. It is throwing an exception in the second try and catch block and prints Deserialization failed. It is however not throwing exception in the first try and catch block. Please reply as soon as you can.
============================================================================


import java.io.*;

public class Save
{

public static void main(String args[])
{

Car a = new Car(45,"Ford");
Car b = new Car(30,"Skyon");

System.out.println (" The cost of a = "+ a.cost);

try
{
ObjectOutputStream os = new ObjectOutputStream( new FileOutputStream("Amey.ser") );
os.writeObject(a);
os.writeObject(b);

System.out.println (" The file is serialized");

os.close();

}

catch(IOException e){System.out.println (" Serialization failed");}

a=null;
b=null;

try
{

FileInputStream fis = new FileInputStream("Amey.ser");
ObjectInputStream is = new ObjectInputStream( fis );
Car a2= (Car) is.readObject();
Car b2= (Car) is.readObject();

System.out.println (" The cost of a after removing it from suspended animation = "+ a.cost);
}

catch( Exception ex) {System.out.println (" Deseriliazation failed");}





}

}
 
Santhosh Kumar
Ranch Hand
Posts: 242
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First and foremost thing to do is never swallow the exceptions in the catch blocks. Either propagate the exception or print it to log/screen.

Your code is failing due to a NullPointerException in and not due to de-serialization.

If you had printed the Exception like



you would have known about the problem and would have saved some time to post a question
 
Amey Rane
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HEY,

I am sorry for that mistake , should have caught it. Sorry, have just started learning intermediate Java.

Thank you for correcting me

Amey
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!