Skip to content
Related Articles

Related Articles

Improve Article

NotSerializableException in Java with Examples

  • Last Updated : 07 Sep, 2021

Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is mainly used in Hibernate, RMI, JPA, EJB, and JMS technologies.

The reverse operation of serialization is called deserialization where byte-stream is converted into an object. The serialization and deserialization process is platform-independent, which means you can serialize an object in a platform and deserialize it on a different platform.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In Java, a NotSerializableException exception is thrown when an instance of a class must implement the Serializable interface. The exception is thrown by either the serialization runtime, or by the instance of the class. The argument for the NotSerializableException is the name of the class.



The NotSerializableException class extends the ObjectStreamException class, which is defined as the superclass of all exceptions specific to Object Stream classes. Also, the ObjectStreamException class extends the IOException which signals that an I/O exception has occurred.

Illustration: 

java.io
Class NotSerializableException
    java.lang.Object
        java.lang.Throwable
            java.lang.Exception
                java.io.IOException
                    java.io.ObjectStreamException
                        java.io.NotSerializableException

Note: All Implemented Interfaces are Serializable interface

Syntax:

public class NotSerializableException 
extends ObjectStreamException

Let us discuss the constructors of this class before a

  1. NotSerializableException(): Constructs a NotSerializableException object.
  2. NotSerializableException(String classname): Constructs a NotSerializableException object with message string.

Example 1:

Java




// Java Program to Illustrate NotSerializableException
// Where Exception Is Thrown
 
// Importing required classes
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
 
// Class 1
// Helper class
class Employee {
 
    // Member variables
    private String id;
 
    // Member methods
 
    // Method 1
    // To get ID of an employee
    public String getId() { return id; }
 
    // Method 1
    // To set ID of an employee
    public void setId(String id)
    {
 
        // this keyword refers to current object itself
        this.id = id;
    }
}
 
// Class 2
// Main Class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
        throws IOException
    {
 
        // Create FileOutputStream class object  to
        // create a file
        FileOutputStream out
            = new FileOutputStream("employee.dat");
 
        // Similarly creating ObjectOutputStream class
        // object
        ObjectOutputStream outputStream
            = new ObjectOutputStream(out);
 
        // Creating objects of class 1
        Employee obj = new Employee();
 
        // Assifning ID to an employee
        obj.setId("001");
 
        // Writing objects to stream
        outputStream.writeObject(obj);
 
        // Good practice is always to
        // Close the stream using close() method
        outputStream.close();
    }
}

 
 



Output : 

Errors in Code
Exception in thread "main" java.security.AccessControlException: access denied ("java.io.FilePermission" "employee.dat" "write")
at java.base/java.security.AccessControlContext.checkPermission(AccessControlContext.java:472)
at java.base/java.security.AccessController.checkPermission(AccessController.java:897)
at java.base/java.lang.SecurityManager.checkPermission(SecurityManager.java:322)
at java.base/java.lang.SecurityManager.checkWrite(SecurityManager.java:752)
at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:225)
at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:126)
at NotSerializableExceptionExample.main(NotSerializableExceptionExample.java:21)                                                    

How to deal with the NotSerializableException

  • The simplest solution is to find the class that throws the exception and makes it implement the Serializable interface. However, this may not be feasible if the class that throws the exception belongs to a third-party library.
  • In case the class refers to non-serializable objects and these objects should not be serialized, then, you can declare these objects as transient. Once a field of a class is declared as transient, then, it is ignored by the serializable runtime.

 

Example 2:

Java




// Java Program to Illustrate NotSerializableException
// where No Exception is Thrown Using Serializable interface
 
// Importing input output class
import java.io.Serializable;
 
// By implementing Serializable interface
// we are allowing Student object to
// be stored in TestFile.txt
 
// Class 1
// Helper class extending to Serializable interface
class Student implements Serializable {
 
    // Member variables of this class
    int id;
    String name;
 
    // Constructor of ths class
    public Student(int id, String name)
    {
        this.id = id;
        this.name = name;
    }
}
 
// Class 2
// Main class
class Persist {
 
    // Main driver method
    public static void main(String args[])
    {
 
        // try block to check for exceptions
        try {
 
            // Creating the object
            Student s1 = new Student(007, "Test");
 
            // Creating stream and writing the object
            FileOutputStream fout
                = new FileOutputStream("TestFile.txt");
            ObjectOutputStream out
                = new ObjectOutputStream(fout);
 
            out.writeObject(s1);
            out.flush();
 
            // Closing the stream to free up memory space
            // using close() method
            out.close();
 
            // Display command to shown proper execution of
            // a program
            System.out.println(
                "Object stored successfully");
        }
 
        // Catch block to handle the exceptions
        catch (Exception e) {
 
            // Print and display the exception on the
            // console
            System.out.println(e);
        }
    }
}

 
 
Output:

Object stored successfully

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :