We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi. I'm trying to use Processing with Encog, and I have two functions that serialize and deserialize a neural network. The sketch contains two functions that I originally wrote in plain Java 7, so it uses try-with-resources. However, when I ran them verbatim in Processing, it gave me this error: Expected LBRACE, found '('
So I expanded out the try-with-resources, like this:
BasicNetwork load() {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream(file));
return (BasicNetwork) in.readObject();
}
catch (ClassNotFoundException e) {
System.err.println("Looks like Encog isn't imported properly :(");
System.exit(1);
return null;
}
catch (IOException e) {
e.printStackTrace();
return null;
}
finally {
in.close();
}
}
But then in.close()
can also throw IOException
, so Processing gave me this error for the finally
block:
Unhandled exception type IOException
I know, ironic. I'm gonna be playing Whac-a-Mole with these pesky exceptions. What should I do about it?
Here is my original code:
File file = new File("data/neural-network.blob");
BasicNetwork load() {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(file))) {
return (BasicNetwork) in.readObject();
}
catch (ClassNotFoundException e) {
System.err.println("Looks like Encog isn't imported properly :(");
System.exit(1);
return null;
}
catch (IOException e) {
e.printStackTrace();
return null;
}
}
Answers
Your code compiles fine. The only problem is that the
in.close()
line also needs to be wrapped in a try/catch block.One approach would be to just wrap the whole thing in a try/catch block. That's not exactly the safest, but for most cases (particularly if this is just something for yourself and not some mission-critical piece of infrastructure) it'll do the job.
If that sounds annoying, then you understand why they added the try-with-resources feature.
The LBRACE is a simple syntax error that is not related to the try-catch code posted here. You need to look at your code before the indicated error position for an extra RBRACE i.e. )
Aha, I changed it to