I have written a method which writes an object to file.
I used generics so also an object derived from Object can be written (I could also accept a parameter of type Object, but this to be more clear).
public static <T extends Object> void write(T item,String path)
throws FileNotFoundException,IOException
{
ObjectOutputStream os;
Object obj=item;
os=new ObjectOutputStream(new FileOutputStream(path));
os.writeObject(obj);
os.close();
}
So the doubt is about the pragmatic: is correct to leave the exceptions go without handling them?because I have also written a second version of the method:
public static <T extends Object> void nothrow_write(T item,String path)
{
ObjectOutputStream os;
Object obj=item;
try
{
os=new ObjectOutputStream(new FileOutputStream(path));
os.writeObject(obj);
os.close();
}
catch(FileNotFoundException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
}
Which method is more pragmatically correct?
The problem of the first one is that if the exception is thrown, the stream remains opened.
1 Answer