简体   繁体   中英

Exceptions allowed while implementing readObject and writeObject method to override default serialization in java?

I know that we have to define methods with the following signatures to override the default serialization process:

private void writeObject(ObjectOutputStream os) {
}

private void readObject(ObjectInputStream is) {
}

Are there any restrictions on the type of exceptions which can be thrown by the above methods? I know that exceptions thrown by a method are not part of method signature but wanted to confirm.

Serializable defines the following exceptions:

private void writeObject(java.io.ObjectOutputStream out)
    throws IOException
private void readObject(java.io.ObjectInputStream in)
    throws IOException, ClassNotFoundException;
private void readObjectNoData()
    throws ObjectStreamException;

This is where the write method gets called:

        try {
            writeObjectMethod.invoke(obj, new Object[]{ out });
        } catch (InvocationTargetException ex) {
            Throwable th = ex.getTargetException();
            if (th instanceof IOException) {
                throw (IOException) th;
            } else {
                throwMiscException(th);
            }
        }

// ...

private static void throwMiscException(Throwable th) throws IOException {
    if (th instanceof RuntimeException) {
        throw (RuntimeException) th;
    } else if (th instanceof Error) {
        throw (Error) th;
    } else {
        IOException ex = new IOException("unexpected exception type");
        ex.initCause(th);
        throw ex;
    }
}

As you can see you can throw any non-runtime exception and it will be wrapped in an IOException, though you should prefer IOExceptions due to shorter stack traces and more useful error messages.

I assume the read method gets called similarly, you might want to check it yourself though.

You can throw any RuntimeException in both Methods

In writeObject(ObjectOutputStream out) you can also throw IOException

In readObject(ObjectInputStream in) yu can also throw IOException and ClassNotFoundException

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM