Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
NotSerializableException in Java with Examples
Next article icon

NotSerializableException in Java with Examples

Last Updated : 05 Jan, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

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 this 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


 


Next Article
NotSerializableException in Java with Examples

P

praveen13kulkarni
Improve
Article Tags :
  • Java
  • Java-Exceptions
Practice Tags :
  • Java

Similar Reads

    NumberFormatException in Java with Examples
    The NumberFormatException occurs when an attempt is made to convert a string with improper format into a numeric value.  That means, when it is not possible to convert a string in any numeric type (float, int, etc), this exception is thrown. It is a Runtime Exception (Unchecked Exception) in Java. I
    3 min read
    Vector setSize() method in Java with Example
    The Java.util.Vector.setSize() is a method of Vector class that is used to set the new size of the vector. If the new size of the vector is greater than the current size then null elements are added to the vector is new size is less than the current size then all higher-order elements are deleted. T
    3 min read
    java.io.UnsupportedEncodingException in Java with Examples
    The java.io.UnsupportedEncodingException occurs when an unsupported character encoding scheme is used in java strings or bytes. The java String getBytes method converts the requested string to bytes in the specified encoding format. If java does not support the encoding format, the method String get
    3 min read
    Serialization and Deserialization in Java with Example
    In Java, serialization plays a very important role it's something that we use a lot in our real life, even if we do not always notice it. Serialization helps us to save the current state of an object so that we can use it further and share complex data between different systems. In this article, we
    8 min read
    Throwable Class in Java with Examples
    Classes and Objects are basic concepts of Object-Oriented Programming which revolve around real-life entities. A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In this article,
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences