0

Hi If a class cannot implement serializable interface and if we try to serialize it, we should get a NotSerializableException. Here I am not getting it. The Cat class doesn't implement Serializable and I try to serialize it. Compiled and run fine why?

 import java.io.*;
 class Cat{}
 class MyTest{
 public static void main(String a[]){
    Cat c = new Cat();
    try{
        FileOutputStream fos = new FileOutputStream("test.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(c);
        oos.close();
        fos.close();
    }
    catch(Exception e){e.getMessage();}
    try{
        FileInputStream fis = new FileInputStream("test.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);
        c =  (Cat)ois.readObject();
        ois.close();
        fis.close();
    }
    catch(Exception e){e.getMessage();}
}
}
user207421
  • 305,947
  • 44
  • 307
  • 483
Shameer
  • 223
  • 1
  • 5
  • 15

1 Answers1

5

It is throwing exceptions, you are just swallowing them with

catch(Exception e){e.getMessage();}

which just calls a method that returns a String, it doesn't log anything.

Use

e.printStackTrace();
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • Found this http://stackoverflow.com/questions/7469316/why-is-exception-printstacktrace-considered-bad-practice.... Is there any other way? – JNL Sep 16 '13 at 20:39
  • @JNL Of course. The methods of `Exception` give you all sorts of options: get the error message, get the stack trace, and you can override or add and use your own. – Sotirios Delimanolis Sep 16 '13 at 20:44