Java Exception.getCause()在尝试查找异常源时返回null
为什么Java Exception.getCause()在尝试查找异常源时返回null,java,objectinputstream,Java,Objectinputstream,为什么System.out.println(e.getCause())给出null? 可以像这样存储整个HashSet集合吗 private void saving() throws IOException, ClassNotFoundException { ObjectOutputStream out = null; try { out = new ObjectOutputStream(new BufferedOutputStream(new FileOutpu
System.out.println(e.getCause())代码>给出null
?
可以像这样存储整个HashSet集合吗
private void saving() throws IOException, ClassNotFoundException {
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(dataFile)));
out.writeObject(c);
} catch (java.io.NotSerializableException e) {
System.out.println(e.getCause());
} finally {
out.close();
}
}
使用了printStackTrace()
而不是getCause()
仍然看不到问题,除了它捕捉到集合的第一个对象,并且集合正在实现Serializable
,所有对象也实现Serializable
,并且线程在声明的位置具有瞬态异常时,使用getCause
方法获取原始原因。在这种情况下,异常没有从任何其他层链接,因此getCause
返回null
。您应该使用e.printStackTrace()
来获取异常的原因。这很可能是因为HashSet
中的一个或多个键/值属于未实现java.io.Serializable
的类型,请使用printStackTrace()
而不是getCause()
是的,您可以保存整个集合(只要它包含实现可序列化的对象)。下面的代码给出了异常的确切原因
try{
// code
}
catch(Exception ex){
Exception exe = new Exception();
String causeString="";
exe.initCause(ex);
if(exe.getCause()!=null && exe.getCause().getCause()!=null)
causeString= exe.getCause().getCause().getLocalizedMessage();
}
处理异常时,通常可以使用printStackTrace()或getMessage()来处理简单的异常消息。在整个集合中,内部的所有类都应该实现可序列化接口。在这种情况下,getCause()和getMessage()都将为null。唯一好的解决方案是理解将抛出什么样的异常类型,并优雅地处理它们。这似乎并不能回答这个问题——尽管它确实有助于进一步的调试
try{
// code
}
catch(Exception ex){
Exception exe = new Exception();
String causeString="";
exe.initCause(ex);
if(exe.getCause()!=null && exe.getCause().getCause()!=null)
causeString= exe.getCause().getCause().getLocalizedMessage();
}