Eclipse's Dead Code warning when it is reachable? - java

Why Eclipse gives me a dead code warning in the fourth line of the following method? How can it not be reachable?
private void writeToSequenceFile() {
try {
CustomFileWriter nBatchWriter = new CustomFileWriter(sequeneceFileName, CONFIG_RESOURCE_NAME, "outputFile");
// The line below is a dead code?
lineBuilder.setString("Line", fileSequenceDate.concat(" ").concat(fileSequenceNo));
lineBuilder.setString("LineFeed", "\r");
nBatchWriter.writeRecord(lineBuilder.toRecord());
nBatchWriter.close();
} catch (Exception ex){
throw new NcoBusinessProgramException("Error Writing To Sequence File!");
}
}

Does it compile?
The only possible way that I can imagine for that line to be unreachable would be if the CustomFileWriter constructor called writeToSequenceFile(), causing infinite recursion, so the next line would never be reached. (Or if the constructor always threw an exception, but that would be a pretty silly way to write it.)

Are you sure it is ? It might be an artefact, try to close and reopen the file, or save all and rebuild.

Related

Given the following snippet, would it be wise to specify the reason of the failure or throw an IOException?

I'm creating a "File Manager" to practice my IO skills. If I'm creating a file, how would I handle an error if file#createNewFile() returns false?
#Override
public void run() {
File file = new File(src + "\\" + srcName);
try {
if (file.createNewFile()) {
MessageHandler.createSuccess(comp);
} else {
throw new IOException();
}
} catch (IOException e) {
MessageHandler.error500(comp);
}
}
Right now I'm simply throwing an IOException to be caught in the next block, but I'm not sure if that is the best idea. It should be fine on the client end but when debugging I would have no idea what went wrong internally.
It depends. I guess there is no single clear answer to this, so other members of the community might view this differently than I do.
According to the Javadoc, createNewFile returns false only if the file already exists.
Therefore, in cases where the file should not be present whatsoever, I also just throw an IOException.
If I have a reason to assume the file could be present, the user interacting with the program should be notified of this problem in some way. How exactly you do this depends on the UI of your program.
The code snippet you showed us does not make much sense. Throwing an exception, just to catch it immediately, isn't very performant (unless the clever Java optimizers eliminate the costly operations).
Your current run() method does:
MessageHandler.createSuccess() if the file didn't exist and could be created (file.createNewFile() returned true).
MessageHandler.error500() if the file didn't exist, but could not be created, e.g. because of not having the necessary permissions (file.createNewFile() threw an IOException).
MessageHandler.error500() if the file already existed (file.createNewFile() returned true). [Are you sure that already having the file is an error?]
For the case number 3, creating, throwing and catching an IOException does not serve any useful purpose (other than guiding the code into the catch clause).
I'd simply rewrite the code to something like
#Override
public void run() {
File file = new File(src + "\\" + srcName);
try {
if (file.createNewFile()) {
MessageHandler.createSuccess(comp);
} else {
MessageHandler.error500(comp);
}
} catch (IOException e) {
MessageHandler.error500(comp);
}
}
You might even find a result code different from 500, better representing the cause of the failure.
Exceptions are a very good way for one method to communicate to the other methods up its caller hierarchy that it wasn't able to do its job. Throwing and catching an exception within one method rarely is a good idea.

How to fix unreported IO Exception. Trying to read a specific line from a .txt file [duplicate]

This question already has an answer here:
What does "error: unreported exception <XXX>; must be caught or declared to be thrown" mean and how do I fix it?
(1 answer)
Closed 8 months ago.
While learning Java I stumble upon this error quite often. It goes like this:
Unreported exception java.io.FileNotFound exception; must be caught or declared to be thrown.
java.io.FileNotFound is just an example, I've seen many different ones. In this particular case, code causing the error is:
OutputStream out = new BufferedOutputStream(new FileOutputStream(new File("myfile.pdf")));
Error always disappears and code compiles & runs successfully once I put the statement inside try/catch block. Sometimes it's good enough for me, but sometimes not.
First, examples I'm learning from do not always use try/catch and should work nevertheless, apparently.
Whats more important, sometimes when I put whole code inside try/catch it cannot work at all. E.g. in this particular case I need to out.close(); in finally{ } block; but if the statement above itself is inside the try{ }, finally{} doesnt "see" out and thus cannot close it.
My first idea was to import java.io.FileNotFound; or another relevant exception, but it didnt help.
What you're referring to are checked exceptions, meaning they must be declared or handled. The standard construct for dealing with files in Java looks something like this:
InputStream in = null;
try {
in = new InputStream(...);
// do stuff
} catch (IOException e) {
// do whatever
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
}
}
}
Is it ugly? Sure. Is it verbose? Sure. Java 7 will make it a little better with ARM blocks but until then you're stuck with the above.
You can also let the caller handle exceptions:
public void doStuff() throws IOException {
InputStream in = new InputStream(...);
// do stuff
in.close();
}
although even then the close() should probably be wrapped in a finally block.
But the above function declaration says that this method can throw an IOException. Since that's a checked exception the caller of this function will need to catch it (or declare it so its caller can deal with it and so on).
Java's checked exceptions make programmers address issues like this. (That's a good thing in my opinion, even if sweeping bugs under the carpet is easier.)
You should take some appropriate action if a failure occurs. Typically the handling should be at a different layer from where the exception was thrown.
Resource should be handled correctly, which takes the form:
acquire();
try {
use();
} finally {
release();
}
Never put the acquire() within the try block. Never put anything between the acquire() and try (other than a simple assign). Do not attempt to release multiple resources in a single finally block.
So, we have two different issues. Unfortunately the Java syntax mixes up the two. The correct way to write such code is:
try {
final FileOutputStream rawOut = new FileOutputStream(file);
try {
OutputStream out = new BufferedOutputStream(rawOut);
...
out.flush();
} finally {
rawOut.close();
}
} catch (FileNotFoundException exc) {
...do something not being able to create file...
} catch (IOException exc) {
...handle create file but borked - oops...
}

Java IO Exception Catching

I need my application to bring up an error in writing to the location /dev/full. Is there anyway I can do this with Java exception handling? I am already throwing and catching IOerrors, so I don't know what the problem is...?
I am reading data from standard in, and compressing it and writing it to standard out.
Writing to /dev/full isn't raising an exception...any ideas on how to raise an exception for this?
There is a Parent Class for all Exceptions that is Exception. If you are not sure which type of exceptions are thrown from try block, use Exception in your last catch block.
something like this
try{
....//code here
}
catch(FileNotFoundException fnfe){
log(fnfe);
}
catch(IOException ioe){
log(ioe);
}
catch(Exception e){
log(e);
}
finally{
....//code here
}
You could write a code for writing all the details of the error and any specific comments you wish to make regarding the class or object so that you can trace the error better inside the catch block.
try
{
//Your code
}
catch(SomeException e)
{
//Create a file, write data to it and close it.
}
I use this technique to save user data in case a file cannot be opened for modifications. Helps because i am sure that the data will be stored at either of the 2 places.
Also, this doesn't affect my further executing of the program as the data is loaded in an object of File. There could be better methods to the above. But this is what my professor showed me. Could be of use.

How to retry opening a properties file in Java

I'm trying to handle an FileNotFoundException in Java by suspending the thread for x seconds and rereading the file. The idea behind this is to edit properties during runtime.
The problem is that the programm simply terminates. Any idea how to realize this solution?
There's a good-old recipe, originally by Bjarne Stroustroup for C++, ported here to Java:
Result tryOpenFile(File f) {
while (true) {
try {
// try to open the file
return result; // or break
} catch (FileNotFoundException e) {
// try to recover, wait, whatever
}
}
}
Do the file loading in a loop and set the variable the condition depends on after the file has been successfully read. Use a try-catch block inside the loop and do the waiting in the catch-block.
Some code snippets would be useful, but one of the following could be the problem:
Your code successfully catches the first FileNotFoundException but after waking up the code does not successfully handle a second one
Another exception is being thrown which is not being handled. Try temporarily wrapping the code in question with a catch (Exception e) to see what exception is being thrown
The program you use to edit the file is 'locking' the properties file and possbily preventing access by your Java code.
Good luck
If the Exception is never caught, the thread is terminated. If this is your main thread, the application ends. Try the following:
try
{
props.load(...);
}
catch (FileNotFoundException ex)
{
Thread.sleep(x * 1000);
props.load(...);
}

Calling a Java main function

I am trying to call another JAR's main function. Now, this main function is enclosed under a try and catch block.
But when the main call returns a "NullPointerException" the program just crashes instead of catching it.
So, for example
try {
somelibary.main()
}
catch (Exception e) {
System.out.println("Exception Caught");
}
This code dosent catch NullPointerException from the main().
Does anyone know the reason y?
Your code, as shown, will definitely catch a NullPointerException thrown by somelibrary.main(). If the application stops anyway due to a NullPointerException there's a fair chance that somelibrary at some point catches the exception, dumps a stack trace and calls system.exit()
In that case the question is not how to catch a NPE, but how to prevent System.exit() from actually exitting.
And the answer to that question can, of course, be found on StackOverflow to, right here. Just install a SecurityManager before the call to someLibrary, and reset the securityManager afterwards.
It's possible that the other main function is doing its own error handling, à la
public static void main(String[] args) {
try {
....
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
If that's what the other main function is doing, then you won't be able to catch its exceptions. Do you have the code for this main function?
With the code you are showing, you will catch also the NullPointerException. But the execution will go on after the catch-block. So the execution of somelibary.main() is stopped in this case. If your main() is not contain more code, the program will end after catching the exception. That's what likely happens. You could post the complete code of your main, to verify this.
Addition: You want to know how to go on with the execution of the program. But in this case somelibrary.main() is stopped by throwing the exception. The only option in the main-class will be a loop, that reexecutes somelibrary.main(). The other possibility is to catch the Exception at some higher level (main input-loop) where you can ignore the problem and go on with the execution of the code. As you say you execute another jars-main I suspect you cannot change the code of the other jar. So you are only left with reexecute the other main:
boolean ended = false;
while (!ended)
{
try {
somelibary.main()
ended = true;
}
catch (Exception e) {
System.out.println("Exception Caught");
}
}
This code restarts the other main on an exception but ends if the other main ends normally.
Perhaps you could execute the main method in another process using Runtime.exec, then capture the result or the error from out/err stream.

Categories