Java Reference
In-Depth Information
Object myObject = null;
try {
myObject = objectIn.readObject();
} catch(ClassNotFoundException e){
e.printStackTrace(System.err);
System.exit(1);
} catch(IOException e){
e.printStackTrace(System.err);
System.exit(1);
}
The
readObject()
method can throw the following exceptions.
ClassNotFoundException
Thrown if the class for an object read from the stream
cannot be found.
InvalidClassException
Thrown if there is something wrong with the class for an
object. This is commonly caused by changing the
definition of a class for an object between writing and
reading the file.
StreamCorruptedException
When objects are written to the stream, additional
control data is written so that the object data can be
validated when it is read back. This exception is thrown
when the control information in the stream is
inconsistent.
OptionalDataException
Thrown when basic types of data are read rather than
an object. For instance, if you wrote a
String
object
using the
writeChars()
method and then attempted
to read it back using the
readObject()
method, this
exception would be thrown.
IOException
Thrown if an error occurred reading the stream.
Clearly, if you do not have a full and accurate class definition for each type of object that you want to
read from the stream, the stream object will not know how to create the object and the read will fail.
The last four of the five possible exceptions are flavors of
IOException
, so you can use that as a
catchall as we have in the code fragment above. However,
ClassNotFoundException
is derived
from
Exception
, so you must put a separate
catch
block for this exception in your program.
Otherwise it will not compile.
As the code fragment implies, the
readObject()
method will return a reference to the object as type
Object
, so you need to cast it to the appropriate class type in order to use it. Note that arrays are
considered to be objects and are treated as such during serialization, so if you explicitly read an array
from a file, you will have to cast it to the appropriate array type.
For example, if the object in the previous code fragment was of type
MyClass
, you could read it back
from the file with the statements: