Tag Archives: InvalidClassException

Java: Serialization Exception Handling


All these exceptions are related to serialization which occurred while doing serialization and deserialization of objects. These exceptions are subclasses of ObjectStreamException which is a subclass of IOException.

Pre-requisite:

Java Serialization exception hierarchy

Exception Description
ObjectStreamException Superclass of all serialization exceptions.
InvalidClassException This exception occurred when  a class cannot be used to restore/deserialize objects for any of these reasons:

  • The class does not match the serialversionUID of the class in the stream.
  • The class contains properties with invalid primitive data types.
  • The Externalizable class doesn’t have a public no-arg constructor.
  • The  Serializable class can’t access the no-arg constructor of its closest non-serializable superclass.
NotSerializableException This exception has thrown by a readObject or writeObject method to terminate serialization or deserialization.
StreamCorruptedException This exception has thrown when some of the meta information modified:

  • If the stream header is invalid.
  • If control information not found.
  • If control information is invalid.
  • JDK 1.1.5 or fewer attempts to call readExternal on a PROTOCOL_VERSION_2 stream.
NotActiveException This exception has thrown if writeObject state is invalid within the following ObjectOutputStream methods:

  • defaultWriteObject
  • putFields
  • writeFields

This exception has thrown if readObject state is invalid within the following ObjectInputStream methods:

  • defaultReadObject
  • readFields
  • registerValidation
InvalidObjectException This exception occured when a restored object cannot be made valid.
OptionalDataException This exception has thrown by readObject when there is primitive data in the stream and an object is expected. The length field of the exception represents the number of bytes that are available in the current block.
WriteAbortedException This exception has thrown when reading a stream terminated by an exception that occurred while the stream was being written.

See Also:

References

Java: Serialization and Deserialization Examples


Serialization is a mechanism to convert the state of an object as a byte stream to persist and traverse of an object. Byte stream makes platform independent i.e One object can serialize in a platform and deserialize in another platform.

Reverse operation of serialization is called deserialization i.e convert byte-stream to object.

Advantages of Serialization

  • Use to save/persist state of an object.
  • Use to travel an object across a network i.e also called and marshaling.

Technically, Serialization and deserialization used in Hibernate, RMI, JPA, EJB and JMS technologies to persist the state of the object as a stream.

Java Serialization and Deserialization

In Java, to make an object Serializable implements java.io.Serializable interface which is a marker interface (has no data member and methods).

See Also:

Object Serialization

We can call writeObject() method of ObjectOutputStream class for serialization of object.

public final void writeObject(Object obj) throws IOException

Object Deserilization

We can call readObject() method of ObjectInputStream class for deserialization of object.

public final Object readObject() throws IOException, ClassNotFoundException

Points to remember

  • The objects of those classes will able to serialize which are implementation java.io.Serializable interface.
  • If the parent class implemented a Serializable interface then the child class doesn’t need to implement it but vice-versa is not true.
  • Internal associated component objects of a class must implement the Serializable interface.
  • Object Constructor never called when an object is deserialized.
  • Static and transient data members of the class are not serialized. If you don’t want to serialize some of the data members make it transient.
  • In the case of array or collection, all the objects of array or collection must be serializable. If any object is not serializable, serialization will be failed.

For Example :

//Implemneted Serilizable interface to make objects of
//ClassA serializable eligible
class ClassA implements Serializable{
//Associate component object Class also need to
//implement Serializable
ClassB ob=new ClassB();
}

What is SerialVersionUID?

On-time of Serialization on an object of Serializable class associate a version called as SerialVersionUID. This version is used during Deserialization to verify that the sender and receiver of a serialized object loaded classes are compatible with respect to serialization.

In case receiver loaded class have different version UID than sender’s class then it will throw an exception as InvalidClassException.

We can explicitly declare SerialVersionUID as long in Serializable class as below:

private static final long serialVersionUID=26L;

Note: Use access modifier as private because this field is not useful for inherited classes.

Recommendation: Always explicitly declare SerialVersionUID for serializable classes with some long value because if not mentioned explicitly then compute at runtime i.e highly sensitive to class details that may vary depending on compiler implementations or any change in class fields etc. which can generate different SerialVersionUID. This different SerialVersionUID may affect the time of the deserialization of the object.

serialver

To manually check serialVersionUID of java classes. JDK provided a tool serialver. We can run this tool as below:

serialver [-classpath classpath] [-show] [classname…]

Example: Serialization and Deserialization

This Employee object needs to serialize and deserialize in the given example. The employee object implements java.io.Serializable marker interface that is required to mark as an object is eligible for serialization.

import java.io.Serializable;

public class Employee implements Serializable {
	int id;
	String name;
	int age;

	public Employee(int id, String name, int age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}
}

Here we have written a separate method for the implementation of serialization and deserialization.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializationAndDeserilizationExample {

	public static void main(String[] args) throws Exception {
		// creating employee object
		Employee e1 = new Employee(111, "Saurabh", 35);

		//serialization of object
		serializeEmployee(e1, "employee.txt");

		//deserialization of object
		e1 = deserializeEmployee("employee.txt");
		System.out.println("Employee Detail :");
		System.out.println("Id :" + e1.id + "\nName: " + e1.name + "\nAge: " + e1.age);
	}

	private static void serializeEmployee(Employee e1, String fileName) throws Exception {
		// writing object into employee file
		FileOutputStream f = new FileOutputStream(fileName);
		ObjectOutputStream out = new ObjectOutputStream(f);
		// Serialize employee object as stream and write in file
		out.writeObject(e1);
		out.flush();
		out.close();
		f.close();
		System.out.println("Employee object Serialize Successfully");
	}

	private static Employee deserializeEmployee(String fileName) throws Exception {
		// Read object stream from file
		ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
		//Deserialize object stream to employee object
		Employee e = (Employee) in.readObject();
		in.close();
		return e;
	}

}

Output

Employee object Serialize Successfully
Employee Detail :
Id :111
Name: Saurabh
Age: 35