I am currently experimenting with the encryption and decryption of objects but I am stumbling upon an EOFException every time my read method is declared. I feel like there is a lot of redundancy within my code trying to deal with all of the exceptions so it would be great if you could tell which catch/throw phrases to remove and how I can resolve this problem. Thanks.
java.io.EOFException points to the line in my code with (** **). All the other lines are NetBeans generated code.
public static void readFromBinary() throws IllegalBlockSizeException, EOFException
{
try {
BufferedReader br3 = new BufferedReader(new FileReader(noteFileName));
if (br3.readLine() != null) {
FileInputStream fINoteStream = new FileInputStream(noteFileName);
ObjectInputStream oINoteStream = new ObjectInputStream(fINoteStream);
while(true){
try{
**SealedObject sObj = (SealedObject)oINoteStream.readObject();**
Note note = (Note) sObj.getObject(new NullCipher());
noteList.add(note);
}
catch(EOFException e){
e.printStackTrace();
break;
}
catch (IllegalBlockSizeException e){
e.printStackTrace();
break;
}
catch (BadPaddingException e){
e.printStackTrace();
break;
}
catch (ClassNotFoundException e){
e.printStackTrace();
break;
}
}
oINoteStream.close();
}
}
catch (FileNotFoundException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
}
}
Method Call in another class:
try{
DataStorage.readFromBinary();
}
catch (IllegalBlockSizeException e)
{
e.printStackTrace();
}
catch (EOFException e)
{
e.printStackTrace();
}
EOFException just means you got to the end of the input. You need to close the inout and break out of the loop. You don't need to print the stack trace. It doesn't have anything to do with SealedObject specifically, just with how object streams work.
You need to decide whether you're catching this exception or throwing it. You shouldn't do both.
Related
I'm using "ObjectInputStream" to load serialized 2D String arrays.
The problem is, My IDE, Intellij-IDEA, will throw an error unless I put a special catch condition for a ClassNotFoundException. However, when I do that it advises, "'catch' branch identical to 'IOException' branch".
I don't know what this is implying I should do.
How can I load serialized objects without getting either advice or an error?
My code:
private String[][] getPossArray(String race, boolean isFirstName) {
String[][] retVal = new String[0][];
try {
FileInputStream fis = new FileInputStream("./res/binary_files/Human_FirstNameString[][].ser");
ObjectInputStream ois = new ObjectInputStream(fis);
retVal = (String[][]) ois.readObject();
ois.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return retVal;
}
Thanks to guleryuz's comment, I found out that the advice from IntelliJ was trying to tell me that I could get rid of the advice notification by changing my catch block to catch (IOException | ClassNotFoundException e) instead of having each catch statement on it's own line.
Old Catch-Block Version:
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
New Catch-Block Version:
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
I have been using Find Bugs in Eclipse and I can not figure out why some of the bugs are coming up or how to fix them. Any ideas or help would be great!
The first bug is (Bug: Exception is caught when Exception is not thrown in banking.primitive.core.ServerSolution.saveAccounts()):
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
The second bug is (Bug: Exception is caught when Exception is not thrown in banking.primitive.core.ServerSolution.saveAccounts()):
out.writeObject(accountMap.get(i));
I tried to change it to :
out.writeObject(accountMap.get(Integer.toString(i)));
The third bug is (Bug: Exception is caught when Exception is not thrown in banking.primitive.core.ServerSolution.saveAccounts()):
} catch (Exception e) {
e.printStackTrace();
throw new IOException("Could not write file:" + fileName);
For the first bug this is with my try block as well. I am lost. I tried to follow you post below, but I am confused. Sorry, I am very new!
public ServerSolution() {
accountMap = new HashMap<String,Account>();
File file = new File(fileName);
ObjectInputStream in = null;
try {
if (file.exists()) {
System.out.println("Reading from file " + fileName + "...");
in = new ObjectInputStream(new FileInputStream(file));
Integer sizeI = (Integer) in.readObject();
int size = sizeI.intValue();
for (int i=0; i < size; i++) {
Account acc = (Account) in.readObject();
//CST316 TASK 1 CHECKSTYLE FIX
if (acc != null) {
accountMap.put(acc.getName(), acc);
}
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
See FindBugs Bug Description:
This method uses a try-catch block that catches Exception objects, but Exception is not thrown within the try block, and RuntimeException is not explicitly caught. It is a common bug pattern to say try { ... } catch (Exception e) { something } as a shorthand for catching a number of types of exception each of whose catch blocks is identical, but this construct also accidentally catches RuntimeException as well, masking potential bugs.
A better approach is to either explicitly catch the specific exceptions that are thrown, or to explicitly catch RuntimeException exception, rethrow it, and then catch all non-Runtime Exceptions, as shown below:
try {
...
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
... deal with all non-runtime exceptions ...
}
I have a program that needs to load data at launch. The data comes from a serialized object. I have a method loadData(), which is called upon construction of the Data class. Sometimes, (I.e. after a loss of saveData, or on first program launch on a new system), the file can be empty. (The file will exist though, the method ensures that).
When I try to run the program, I recieve an EOFException. So, in the method, I try to catch it, and just print a line to the console explaining what happened and return to the caller of the method. (so, upon return, the program will think loadData() is complete and has returned. However, it still crashes throwing the exception without printing a line to the console or anything. It is like it is totally ignoring the catch I have in place.
CODE:
protected void loadData()
{
// Gets/creates file object.
saveFileObject = new File("savedata.ser");
if(!saveFileObject.exists())
{
try
{
saveFileObject.createNewFile();
}
catch(IOException e)
{
System.out.println("Uh oh...");
e.printStackTrace();
}
}
// Create file input stream
try
{
fileIn = new FileInputStream(saveFileObject);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
// Create object input stream
try
{
inputStream = new ObjectInputStream(fileIn);
}
catch(IOException e)
{
e.printStackTrace();
}
// Try to deserialize
try
{
parts = (ArrayList<Part>)inputStream.readObject();
}
catch(EOFException e)
{
System.out.println("EOFException thrown! Attempting to recover!");
return;
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
// close input stream
try
{
inputStream.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
Any help please?
Try writing your code like :
protected void loadData() {
// Gets/creates file object.
saveFileObject = new File("savedata.ser");
try {
if (!saveFileObject.exists()) {
saveFileObject.createNewFile();
}
// Create file input stream
fileIn = new FileInputStream(saveFileObject);
// Create object input stream
inputStream = new ObjectInputStream(fileIn);
// Try to deserialize
parts = (ArrayList<Part>) inputStream.readObject();
// close input stream
inputStream.close();
} catch (EOFException e) {
System.out.println("EOFException thrown! Attempting to recover!");
} catch (IOException e) {
System.out.println("Uh oh...");
e.printStackTrace();
}
}
Also note that EOFException is a sub-class of IOException
How about making one try and then making catches respectively like here?
Can we catch an exception type twice in the main method with different messages? I want to print out a different warning.
Ex:
try {
// some code
} catch (NumberFormatException e) {
System.out.println("Wrong input!");
} catch (NumberFormatException e) {
System.out.println("No valid number!");
}
You cannot catch the same exception type (like NumberFormatException) twice. I suggest you catch it once but in the catch block, you print two messages instead.
As i understand your comments you want to display the right message for your exception:
try {
// some code
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
}
You can´t catch the same exception twice.
What you can do is to throw a custom exception in your code and catch it if you want a different behaviour.
try{
...
throw new YourException(yourMessage);
}catch(YourException e){
}
You can´t catch the same exception twice.
Consider the following example,
try {
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
throw new SampleException(e);
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
Here,
Both handlers print an error message. The second handler does nothing else. By catching any IOException that's not caught by the first handler, it allows the program to continue executing.
The first handler, in addition to printing a message, throws a user-defined exception.
I have two arrays that I want to print to separate files. Here's my code:
try {
PrintStream out = new PrintStream(new FileOutputStream(
"Edges.txt"));
for (i = 0; i < bcount; i++) {
out.println(b[i][0] + " " + b[i][1]);
}
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
try {
PrintStream out = new PrintStream(new FileOutputStream(
"Nodes.txt"));
for (i = 0; i < bigbIter; i++) {
out.println(bigb[i]);
}
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
If I only use the first set of try / catch / catch, it works perfectly. But when I use both it doesn't work, giving me the errors "illegal start of type ... } catch" and "error: class, interface, or enum expected". What am I doing wrong?
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
You have an extra }, which throws off the parser and gives you lots of errors.
You should write a method to write to the file. Just pass the file name and data. You should see that you have too many closing brackets, get your IDE to highlight brackets.
Lesson is just don't copy/paste and then edit the catch block when you want it again!
Edit: Also in java 7 you can have multiple catches in one block, it is better to do this:
catch (FileNotFoundException | IOException e)
{
}