繁体   English   中英

实现readObject和writeObject方法以覆盖Java中的默认序列化时是否允许异常?

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

我知道我们必须使用以下签名定义方法,以覆盖默认的序列化过程:

private void writeObject(ObjectOutputStream os) {
}

private void readObject(ObjectInputStream is) {
}

上述方法可引发的异常类型是否有限制? 我知道方法抛出的异常不是方法签名的一部分,而是要确认。

可序列化定义以下异常:

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

这是调用write方法的地方:

        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;
    }
}

如您所见,您可以抛出任何非运行时异常,并且它将包装在IOException中,尽管由于较短的堆栈跟踪和更有用的错误消息,您应该首选IOExceptions。

我假设read方法被类似地调用,但是您可能需要自己检查一下。

您可以在两个方法中抛出任何RuntimeException

在writeObject(ObjectOutputStream out)中,您还可以抛出IOException

在readObject(ObjectInputStream in)中,yu也可以抛出IOExceptionClassNotFoundException

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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