What happens if an exception is thrown during the serialization process?

When an exception occurs during serialization, the serialization process is interrupted and the object is not successfully converted into a byte stream. As a result, the object's state cannot be stored, transferred, or reconstructed later.

Key Points: • Serialization fails immediately when a non-serializable object is encountered. • NotSerializableException is commonly thrown if a class does not implement the Serializable interface. • IOException and its subclasses can also occur due to file, network, or stream-related issues. • Partial object state should not be relied upon because the serialization process is considered unsuccessful.

Example: Suppose an Employee object contains an Address object. If Employee implements Serializable but Address does not, serialization will fail with a NotSerializableException when attempting to write the Employee object to a stream.

Code Example:

class Address {
    private String city;
}

class Employee implements Serializable {
    private Address address;
}

ObjectOutputStream out =
        new ObjectOutputStream(new FileOutputStream("employee.ser"));
out.writeObject(new Employee()); // Throws NotSerializableException

Interview Tip: A concise interview answer is: If an exception occurs during serialization, the process fails and the object is not written successfully. The most common exception is NotSerializableException when an object in the object graph does not implement Serializable. Other I/O-related issues may result in IOException, preventing the object from being converted into a byte stream.