krund krund - 18 days ago 6
Java Question

Jva ArrayIndexOutOfBounds doesn't fire

When this code executed without arguments(

args = []
), I got
NullPointerException
while attempting to close file but where is an
ArrayIndexOutOfBoundsException
? All catch statements just add a custom message, and rethrows exceptions without handling so I should get any exception on console. Execution jumps from
if(args[0].equals(""))
to finally block.

public class FileIO {
//args: output filename string, string to write
public static void main(String args[]) throws Exception, IOException{

//args = []
File output_file = null;
FileWriter output = null;
try {
if(args[0].equals("")){ //where is ArrayIndexOutOfBounds?
throw new Exception("Filename is invalid");
}
output_file = new File(args[0]);
output = new FileWriter(output_file);
}
catch (IOException e){
throw new IOException("Error while creating output file", e);
}
finally{
try{
output.close();//NullPointerException here
}
catch (IOException e){
throw new IOException("Error closing output file", e);
}
}

}
}

Answer

There is an ArrayIndexOutOfBoundsException but that causes the finally block to be executed and there you get the NullPointerException (NPE) since output is not yet set.

The finally block is always executed, but if an Exception is thrown inside that block, this Exception will be thrown from the try-finally block.

See Java Language Specification:

...

If a try or catch block in a try-finally or try-catch-finally statement completes abruptly, then the finally clause is executed during propagation of the exception, even if no matching catch clause is ultimately found.

If a finally clause is executed because of abrupt completion of a try block and the finally clause itself completes abruptly, then the reason for the abrupt completion of the try block is discarded and the new reason for abrupt completion is propagated from there.

...

Note: it is advised not to use Exceptions for controlling program flow... much better to test for the length of args, at least it makes the code easier to understand!