Does finally completely execute if an exception is thrown within finally block - java

so I have a bit of code here and I'm not sure entirely how it would react in the event that the reader.close() method throws an exception.
public void someMethod(String s) throws IOException{
BufferedReader reader = Files.newBufferedReader(filePath,cs);
listRWLock.readLock().lock();
try{
//miscellaneous code involving reading
}finally{
reader.close()
listRWLock.readLock().unlock()
}
}
ListRWLock is a ReentrantReadWriteLock. In the event that the reader.close() method throws an exception, would the statement after it fail to execute? I've tried searching for the topic, and while I've gotten something about finally executing in the event of return statements, I haven't managed to find details on what happens if an exception is thrown within the finally block.
Thanks in advance.

Basically, finally clauses are there to ensure proper release of a resource. However, if an exception is thrown inside the finally block, that guarantee goes away.
An issue for which there's no really neat solution is that code in the finally block could itself throw an exception. In this case, the exception in the finally block would be thrown from the exception instead of any exception occurring inside the try block. Since code in the finally block is intended to be "cleanup" code, we could decide to treat exceptions occurring there as secondary, and to put an excplicit catch:
public int readNumber(File f) throws IOException, NumberFormatException {
BufferedReader br = new BufferedReader(new
InputStreamReader(new FileInputStream(f), "ASCII"));
try {
return Integer.parseInt(br.readLine());
} finally {
try { br.close(); } catch (IOException e) {
// possibly log e
}
}
}
Some other things to note about finally blocks:
The same 'overriding' problem that we mentioned with exceptions
occurs when returning a value from a finally block: this would
override any return value that the code in the try block wanted to
return. In practice, returning a value from a finally clause is rare
and not recommended.
Actually exiting the program (either by calling System.exit() or by
causing a fatal error that causes the process to abort: sometimes
referred to informally as a "hotspot" or "Dr Watson" in Windows)
will prevent your finally block from being executed!
There's nothing to stop us nesting try/catch/finally blocks (for
example, putting a try/finally block inside a try/catch block, or
vice versa), and it's not such an uncommon thing to do.

You can do something like this:
try{
//miscellaneous code involving reading
}finally{
handlePossibleException(reader);
listRWLock.readLock().unlock()
}
handlePossibleException(BufferedReader reader) {
try {
if (reader != null) {
reader.close();
}
} catch( Exception e ) {
log.e( "reader.close() Exception: ", e );
}
}

You should test this,
but if try throws IO Exception, then your reader wont close.
Maybe have
catch(IOException ex){
reader.close()

An exception can happen anywhere in your code, including finally block, so you have to catch it as anywhere else in your code. Check the following post to get some ideas about the ways you can handle such situation:
throws Exception in finally blocks

Related

Java - catch/rethrow behavior [duplicate]

This question already has answers here:
Exception thrown in catch and finally clause
(12 answers)
Closed 1 year ago.
I have this piece of Java code.
void convertFile() {
try{
.....
}catch (Exception e) {
logError("Error in convertJsonFile", e);
throw e;
}finally{
if (writer!=null) {
writer.close();
writer = null;
}
if (fos!=null) {
fos.close();
fos = null;
}
ms2 = System.currentTimeMillis();
logInfo(String.format("Time elapsed: %d seconds.", ((ms2-ms1)/1000)));
logInfo("File conversion complete.");
}
return f + "_changed.xml";
}
The catch block logs and rethrows the Exception.
But it seems the finally block also throws a RuntimeException.
Will the finally block be executed if the catch block rethrows Exception as done here?
If I remember correctly finally block will be executed even in this case.
OK if so... what will happen if we enter the catch block (it rethrows), then we enter the finally block, and the finally block also throws a RuntimeException at this line writer.close(); ? Which exception will be thrown from this whole method - the rethrown one from the catch block, or the RuntimeException from the finally block?!
I think the RuntimeException will be the final outcome of the method and we will never reach the line in the catch block which rethrows. Because I guess the line which rethrows is executed after the finally block. But I am not sure. I got really confused.
Could someone clear my doubts here?
Seems I have forgotten some of these details.
And I have no decent access to the logs, they are in Elastic/Kibana and access to them is a real pain.
Yes, finally block will be executed
The exception from finally block will be thrown in this case. Thus, exception from catch block will be lost.

try-with-resource vs ordinary code with explicit close()-call [duplicate]

This question already has answers here:
What's the purpose of try-with-resources statements?
(7 answers)
Closed 2 years ago.
I have been looking at code and I have seen try with resources. I have used the standard try-catch statement before and it looks like they do the same thing. So my question is Try With Resources vs Try-Catch what are the differences between those, and which is better.
Here is a try with resources :
objects jar = new objects("brand");
objects can= new objects("brand");
try (FileOutputStream outStream = new FileOutputStream("people.bin")){
ObjectOutputStream stream = new ObjectOutputStream(outStream);
stream.writeObject(jar);
stream.writeObject(can);
stream.close();
} catch(FileNotFoundException e) {
System.out.println("sorry it didn't work out");
} catch(IOException f) {
System.out.println("sorry it didn't work out");
}
The main point of try-with-resources is to make sure resources are closed reliably without possibly losing information.
When you don't use try-with-resources there's a potential pitfall called exception-masking. When code in a try block throws an exception, and the close method in the finally also throws an exception, the exception thrown by the try block gets lost and the exception thrown in the finally gets propagated. This is usually unfortunate, since the exception thrown on close is something unhelpful while the informative one is the one thrown from within the try block. (So instead of seeing the SQLException that tells you which referential integrity constraint was violated, you're shown something like BrokenPipeException where closing the resource failed.)
This exception-masking is an annoying problem that try-with-resources prevents from happening.
As part of making sure exception-masking wouldn't lose important exception information, when try-with-resources was developed they had to decide what to do with the exceptions thrown from the close method.
With try-with-resources, if the try block throws an exception and the close method also throws an exception, then the exception from the close block gets tacked on to the original exception:
... there are situations where two independent exceptions can be thrown in sibling code blocks, in particular in the try block of a try-with-resources statement and the compiler-generated finally block which closes the resource. In these situations, only one of the thrown exceptions can be propagated. In the try-with-resources statement, when there are two such exceptions, the exception originating from the try block is propagated and the exception from the finally block is added to the list of exceptions suppressed by the exception from the try block. As an exception unwinds the stack, it can accumulate multiple suppressed exceptions.
On the other hand if your code completes normally but the resource you're using throws an exception on close, that exception (which would get suppressed if the code in the try block threw anything) gets thrown. That means that if you have some JDBC code where a ResultSet or PreparedStatement is closed by try-with-resources, an exception resulting from some infrastructure glitch when a JDBC object gets closed can be thrown and can rollback an operation that otherwise would have completed successfully.
Without try-with-resources whether the close method exception gets thrown is up to the application code. If it gets thrown in a finally block when the try block throws an exception, the exception from the finally block will mask the other exception. But the developer has the option of catching the exception thrown on close and not propagating it.
You missed something, the finally block. The try-with-resouces will make it something like,
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream("people.bin");
ObjectOutputStream stream = new ObjectOutputStream(outStream);
stream.writeObject(jar);
stream.writeObject(can);
stream.close();
} catch(FileNotFoundException e) {
System.out.println("sorry it didn't work out");
} catch(IOException f) {
System.out.println("sorry it didn't work out");
} finally {
if (outStream != null) {
try {
outStream.close();
} catch (Exception e) {
}
}
}
Which means you really wanted something like (never swallow exceptions),
try (FileOutputStream outStream = new FileOutputStream("people.bin");
ObjectOutputStream stream = new ObjectOutputStream(outStream);) {
stream.writeObject(jar);
stream.writeObject(can);
// stream.close(); // <-- closed by try-with-resources.
} catch(FileNotFoundException e) {
System.out.println("sorry it didn't work out");
e.printStackTrace();
} catch(IOException f) {
System.out.println("sorry it didn't work out");
e.printStackTrace();
}
The only difference is that try-resource is adding automatically resource.close();
as you would do in finally block
Any object (either the class or their superclass) that implements java.lang.AutoCloseable or java.io.Closeable
can only be used in try-with-resource clause.
AutoClosable interface is the parent interface and Closable interface extends the AutoClosable interface.AutoClosable interface has method close which throws Exception while Closable interface has method that throws IOException.
We can also have catch and finally block followed by try-with-resource like ordinary try, catch and finally, but catch and finally block only get executed once the resource declared inside the try-with-resource clause is closed.
Succinctly it is syntactic sugar to support the AutoClosable interface and call the close() method for you for any outcome.

what's try method means in java? [duplicate]

This question already has answers here:
What's the purpose of try-with-resources statements?
(7 answers)
Closed 2 years ago.
I have been looking at code and I have seen try with resources. I have used the standard try-catch statement before and it looks like they do the same thing. So my question is Try With Resources vs Try-Catch what are the differences between those, and which is better.
Here is a try with resources :
objects jar = new objects("brand");
objects can= new objects("brand");
try (FileOutputStream outStream = new FileOutputStream("people.bin")){
ObjectOutputStream stream = new ObjectOutputStream(outStream);
stream.writeObject(jar);
stream.writeObject(can);
stream.close();
} catch(FileNotFoundException e) {
System.out.println("sorry it didn't work out");
} catch(IOException f) {
System.out.println("sorry it didn't work out");
}
The main point of try-with-resources is to make sure resources are closed reliably without possibly losing information.
When you don't use try-with-resources there's a potential pitfall called exception-masking. When code in a try block throws an exception, and the close method in the finally also throws an exception, the exception thrown by the try block gets lost and the exception thrown in the finally gets propagated. This is usually unfortunate, since the exception thrown on close is something unhelpful while the informative one is the one thrown from within the try block. (So instead of seeing the SQLException that tells you which referential integrity constraint was violated, you're shown something like BrokenPipeException where closing the resource failed.)
This exception-masking is an annoying problem that try-with-resources prevents from happening.
As part of making sure exception-masking wouldn't lose important exception information, when try-with-resources was developed they had to decide what to do with the exceptions thrown from the close method.
With try-with-resources, if the try block throws an exception and the close method also throws an exception, then the exception from the close block gets tacked on to the original exception:
... there are situations where two independent exceptions can be thrown in sibling code blocks, in particular in the try block of a try-with-resources statement and the compiler-generated finally block which closes the resource. In these situations, only one of the thrown exceptions can be propagated. In the try-with-resources statement, when there are two such exceptions, the exception originating from the try block is propagated and the exception from the finally block is added to the list of exceptions suppressed by the exception from the try block. As an exception unwinds the stack, it can accumulate multiple suppressed exceptions.
On the other hand if your code completes normally but the resource you're using throws an exception on close, that exception (which would get suppressed if the code in the try block threw anything) gets thrown. That means that if you have some JDBC code where a ResultSet or PreparedStatement is closed by try-with-resources, an exception resulting from some infrastructure glitch when a JDBC object gets closed can be thrown and can rollback an operation that otherwise would have completed successfully.
Without try-with-resources whether the close method exception gets thrown is up to the application code. If it gets thrown in a finally block when the try block throws an exception, the exception from the finally block will mask the other exception. But the developer has the option of catching the exception thrown on close and not propagating it.
You missed something, the finally block. The try-with-resouces will make it something like,
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream("people.bin");
ObjectOutputStream stream = new ObjectOutputStream(outStream);
stream.writeObject(jar);
stream.writeObject(can);
stream.close();
} catch(FileNotFoundException e) {
System.out.println("sorry it didn't work out");
} catch(IOException f) {
System.out.println("sorry it didn't work out");
} finally {
if (outStream != null) {
try {
outStream.close();
} catch (Exception e) {
}
}
}
Which means you really wanted something like (never swallow exceptions),
try (FileOutputStream outStream = new FileOutputStream("people.bin");
ObjectOutputStream stream = new ObjectOutputStream(outStream);) {
stream.writeObject(jar);
stream.writeObject(can);
// stream.close(); // <-- closed by try-with-resources.
} catch(FileNotFoundException e) {
System.out.println("sorry it didn't work out");
e.printStackTrace();
} catch(IOException f) {
System.out.println("sorry it didn't work out");
e.printStackTrace();
}
The only difference is that try-resource is adding automatically resource.close();
as you would do in finally block
Any object (either the class or their superclass) that implements java.lang.AutoCloseable or java.io.Closeable
can only be used in try-with-resource clause.
AutoClosable interface is the parent interface and Closable interface extends the AutoClosable interface.AutoClosable interface has method close which throws Exception while Closable interface has method that throws IOException.
We can also have catch and finally block followed by try-with-resource like ordinary try, catch and finally, but catch and finally block only get executed once the resource declared inside the try-with-resource clause is closed.
Succinctly it is syntactic sugar to support the AutoClosable interface and call the close() method for you for any outcome.

Catching thrown exceptions with an Exception class I created

In GraphicsFileNotFoundException.java all I have is an import of FileNotFoundException and the class GraphicsFileNotFoundException which extends FileNotFoundException.
In my main java file, I'm trying to read in a graphics file with the method getGraphicsFile which throws GraphicsFileNotFoundException.
My brain is pooped after a good 40 minutes trying to find out how to catch this exception. I've tried using a try-catch block and catching GraphicsFileNotFoundException but I still get the error
unreported exception GraphicsFileNotFoundException ; must be caught
or declared to be thrown.
public void getGraphicsFile(String fileName) throws GraphicsFileNotFoundException {
String graphics = "";
Scanner getGraphics = null;
try {
getGraphics = new Scanner(new File(fileName));
}
catch (GraphicsFileNotFoundException e){
System.out.println("Error! File can't be found :/");
}
You need to either properly extend the FileNotFoundException class or manually throw an exception inside your try block.
Assuming this is for an assignment (I'm not sure why else you'd need to specifically extend this exception) you'll need to take another look at your GraphicsFileNotFoundException class and make sure that it does what it needs to.
To throw an exception, simply write your condition and the throw statement:
if(needToThrow) {
throw new GraphicsFileNotFoundException();
}
To catch an exception, surround the throw statement with a try block immediately followed by a catch block.
try {
// code here
if(needToThrow) {
throw new GraphicsFileNotFoundException();
}
}
catch(GraphicsFileNotFoundException e) {
// handle the error (print stack trace or error message for example)
e.printStackTrace(); // this is printing the stack trace
}
I recommend using Eclipse if you aren't already because many times it will offer to surround throw statements that need to be caught with a automatically generated try catch block.

What is the correct way to silently close InputStream in finally block without losing the original exception?

I am wondering if the below code closes InputStream in finally block correctly
InputStream is = new FileInputStream("test");
try {
for(;;) {
int b = is.read();
...
}
} finally {
try {
is.close();
} catch(IOException e) {
}
}
If an exception happens during is.read() will be it ignored / suppressed if an exception happens during is.close()?
Best way is to use Java 7 and use try with resources, or do same thing manualy and add exception from closing as suppressed exception.
Pre Java 7:
If you are throwing your custom exception, you can add in it supressed exception like it is done in Java 7 (in your exception create fields List suppressed and put there exceptions from close operation and when dealing with your exception, look there too.
If you cannot do that, I don't know anything better than just log it.
examples:
from Java tutorials
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
but better form is:
static String readFirstLineFromFile(String path) throws IOException {
try (FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr)) {
return br.readLine();
}
}
This way even if creation of FileReader is succesfull but creation of BufferedReader fails (eg not enough memory), FileReader will be closed.
You can close it with IOUtils from https://commons.apache.org/proper/commons-io/
public void readStream(InputStream ins) {
try {
//do some operation with stream
} catch (Exception ex) {
ex.printStackTrace();
} finally {
IOUtils.closeQuietly(ins);
}
}
The Java 6 specs say
If execution of the try block completes abruptly for any other reason R, then the finally block is executed. Then there is a choice:
If the finally block completes normally, then the try statement completes abruptly for reason R.
If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).
So you are right, you will lose the original exception.
The solution probably is to write your finally block so defensively that it is a bigger surprise (worth propagating) if the finally block fails than if an exception comes out of the try catch block.
So, for example, if it is possible that the stream may be null when you try to close it, check it:
InputStream is = new FileInputStream("test");
try {
for(;;) {
int b = is.read();
...
}
} finally {
try {
if( is!=null ) {
is.close();
}
} catch(IOException e) {
}
}
In Java 7, Alpedar's solution is the way to go of course.
The exception from is.close() will be suppressed and the exception from is.read() will be the one that propagates up.
With the code you posted:
If is.close() throws an IOException, it gets discarded and the original exception propagates.
If is.close() throws something else (a RuntimeException or an Error), it propagates and the original exception is discarded.
With Java 7, the correct way to close an InputStream without loosing the original exception is to use a try-with-resources statement:
try (InputStream is = new FileInputStream("test")) {
for(;;) {
int b = is.read();
// ...
}
}
Prior to Java 7, what you do is just fine, except you may want to catch all exceptions instead of just IOExceptions.
Based on your code sample if an exception occurs at the int b = is.read(); point, then the exception will be raised higher up the call chain.
Note though that the finally block will still execute and if the Inputstream invalid another exception will be thrown, but this exception will be "swallowed", which may be acceptable depending on your use case.
Edit:
Based on the title of your question, I would add that what you have is fine in my opinion. You may want to additionally add a catch block to explicitly handle (or perhaps wrap) any exception within the first try block, but it is also acceptable to let any IO exceptions raise up - this really depends on your API. It may or may not be acceptable to let IO exceptions raise up. If it is, then what you have it fine - if it isn't then you may want to handle/wrap the IO exception with something more suitable to your program.
How about the next solution:
InputStream is = new FileInputStream("test");
Exception foundException=null;
try {
for(;;) {
int b = is.read();
...
}
} catch (Exception e){
foundException=e;
}
finally {
if(is!=null)
try {
is.close();
} catch(IOException e) {
}
}
//handle foundException here if needed
If an exception happens during is.read() will be it ignored / suppressed if an exception happens during is.close()?
Yes. You have a catch block for the exception in close() which does not re-throw the exception. Ergo it is not propagated or rethrown.
This is the sample to help to understand your problem,
if you declare the scanner in the try-catch block it will give compiler warning the resource is not closed.
so either make it locally or just in try()
import java.util.InputMismatchException;
import java.util.Scanner;
class ScanInt {
public static void main(String[] args) {
System.out.println("Type an integer in the console: ");
try (Scanner consoleScanner = new Scanner(System.in);) {
System.out.println("You typed the integer value: "
+ consoleScanner.nextInt());
} catch (InputMismatchException | ArrayIndexOutOfBoundsException exception) {
System.out.println("Catch Bowled");
exception.printStackTrace();
}
System.out.println("----------------");
}
}

Categories

Resources