DesirePRG
DesirePRG

Reputation: 6378

Java object serialized without implementing serializable interface

I have the following code.

Animal.java

   public class Animal{
        String name;
        int age;

        public Animal(){
            name="default name";
            age=0;
        }

    }

Cat.java

  public class Cat extends Animal{
        int legs;
        public Cat(){
            super();
            this.legs=10;
        }
    }

Test.java

import java.io.*;

public class Test{

    public static void main(String[] args){

        try{
            Cat c1 = new Cat();
            FileOutputStream fileStream = new FileOutputStream("myobjects.ser");
            ObjectOutputStream objectStream = new ObjectOutputStream(fileStream);
            objectStream.writeObject(c1);
        }catch(Exception e){
            e.printStackTrace();
        }   

    }
}

This code works without any issue. There is no exception thrown. I was expecting an exception because the cat class has not implemented serializable interface.

Why did my code work?

Upvotes: 3

Views: 1152

Answers (2)

Bassinator
Bassinator

Reputation: 1724

The program DOES throw an exception, you just aren't looking in the right place.

The method e.printStackTrace() prints to the System.err (STDERR) stream, NOT to the standard console output (STDOUT). It is highly likely that you are not looking at the right stream. Most IDE's will show System.err but I can't speak for yours.

A fix would be calling System.out.println(e.getMessage()). This will print the exception message to STDOUT. If you want to print the stack trace, you should call e.printStackTrace(System.out).

It is better practice to find a way to view the System.err (STDERR) stream, as the typical System.out is used for normal program output, not errors. You can call System.err.println(e.getMessage()) to get the exception message, and e.printStackTrace(System.err) to get the stack trace.

Upvotes: 2

Ebin
Ebin

Reputation: 201

First of all, you shouldn't be catching "Exception". Bad practice.

Secondly, if you want to "view" the exception, let the main() method throw the NotSerializableException (using throws).

Upvotes: -1

Related Questions