I'm going through the examples in Sun Certified Programmer For Java 5 guide by Bert Bates and Kathy Sierra. When I reach chapter 6 page 447 ( the example on Serialization) , i try to code the example but my code was able to run successfully without the java.io.NotSerializableException. Even I did not code both classes to implement the Serializable interface. Did I left out anything or did something wrong?
Here's the full code. Thanks in advance!
EDIT by mw: Added Code Tags and disabled smilies. [ April 07, 2007: Message edited by: marc weber ]
You have coded your program very nicely. You have to do one thing only to face the reality of serialization:
Modify your code with following:
Or whereever you have put the catch clause, put e.printStackTrace(); or whatever "exception reference variable name".("dot")printStackTrace(); statement and see what is truth.
Note: You are catching the exceptions and hiding yourself to watch even if they were thrown or not. You program throws exceptions both the times (serializing and deserializing) because of the obvious fact that your classes do not implement the Serializable interface.
Thanks and Regards, cmbhatt [ April 07, 2007: Message edited by: Chandra Bhatt ]
As Chandra pointed out, your code does, in fact, throw a NotSerializableException. However, you're not seeing it because you catch the exception and do nothing with it. If you add a println, you will see it...
From this, I think you can see why catching an exception and doing nothing with it is a Bad Idea.
Now, why does it look like you've successfully serialized the object and got it back? Because the variable "mydog" is still pointing to the original object. You can see this by setting mydog to null after serializing it out. Then, if the serialization was not successful, you will get a NullPointerException when you try to output the "after" lines. If the serialization is successful, then the output will be as expected. [ April 07, 2007: Message edited by: marc weber ]
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org