Safe try/catch java - java

try {
bufferedReader = new BufferedReader(new FileReader(new File(file,FILENAME)));
String readLine = bufferedReader.readLine();
//do stuff
} catch(Exception e) {
throw e;
} finally {
if (bufferedReader!=null)
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
will the bufferedReader closing be invoked in any case in this code?

yes it invokes in any case( if it is not null in you case).According to java docs
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
If you are using Java7 then I strongly recommond to use try-with-resources Statement.Then you do not require to write the finally block in your code.
try-with-resouce example
try (BufferedReader bufferedReader =
new BufferedReader(new FileReader(new File(file,FILENAME)));) {
String readLine = bufferedReader.readLine();
//do stuff
} catch(Exception e) {
throw e;
}
Note:
finally block won't execute in only one case. That is when JVM shutdown(generally with System.exit() statement or when the JVM process is killed externally). In all other cases the finally is guaranteed to execute

Finally is always executed, even if the exception is thrown or not. So it will execute the bufferedReader.close(); when bufferedReader is not null

I would refer you to this question:
In Java, is the "finally" block guaranteed to be called (in the main method)?
Basically, the finally block will always get run, with one exception: If the JVM exits before the finally block executes.
As to whether the bufferedReader executing - as written, so long as it's not null, yes, with the above noted exception

Yes, this code will close bufferedReader in any situation. But in general the code looks like a mess. Java 7 try-with-resources is the best solution of closing resources
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(file,FILENAME))) {
//do stuff
}

finally in a try/catch block means that it will happen no matter what.
Also, the exception would be better stated as IOException.
There is really no reason to have a catch block throw an exception in this situation.
Note: It is true that invoking System.exit() will terminate your could as soon as it is encountered and will result in the application being terminated by the JVM (Java Virtual Machine).

Related

Java 'finally' clause in a nested 'try' block

Will the following finally clause be executed, if an exception is thrown by the PrintWriter?
try{
PrintWriter out = new PrintWriter(filename);
try {
//output
} finally {
out.close();
}
} catch {
//handle exception
}
If the PrintWriter throws an exception, then the nested try block will never get executed, but why the nested finally clause will still be executed, even it's nested and skipped?
Updates:
I ran some tests, if an exception is thrown before the nested try clause, that nested finally will not be executed.
If the exception is thrown inside the nested try clause, then the inner finally and the outter catch will be executed.
No because the inner try block will not be reached when an exception occurs before and therefore the finally block is not reached either.
Finally block is always executed whether exception is handled or not. Even though their is an error and it reaches to catch block, it will go to finally block to execute the piece of code.
finally block is a block that is used to execute important code such
as closing connection, stream etc.
So, Inside try{} block you placed try and finally, but you asked about the catch of outside try ,thus its not going inside the first try block.That finally wont work.
P.S. : If you put finally something like this:
try{
try{...}
finally{...}
}catch(Exception e){...}
finally{... }
//in case of exception also , the outside finally is going to work.
P.S.: Though you got your answer , but the concept is for reference of other naive programmers
An uglier variant (sometimes generated by the IDE) one sees also:
// *** UGLY
PrintWriter out = null;
try {
out = new PrintWriter(filename);
//output
} catch (IOException e) {
//handle exception
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e2) {
// IGNORE
}
}
}
That explains the code a bit: as close may throw an IOException too, the code becomes cumbersome. Your code still needs nested exceptions.
With try-with-resources this can & should be written as:
try (PrintWriter out = new PrintWriter(filename)) {
//output
} catch (IOException e) {
//handle exception
} // Automatically closes.
And no longer nested exceptions.
The biggest advantage is that you need not catch any exception, and just add a throws IOException in the method signature.

Program freezes on bufferedreader close

Program freezes when closing buffered reader. Using forge modding API for minecraft, however I've had this issue before with standalone server side code. This particular code worked fine and then randomly started giving me this issue, not sure how to go about fixing this..
The close method:
public static void closeConnection() {
if (keepConnection) {
keepConnection = false;
try {
bufferedReader.close();
printWriter.close();
socket.close();
}
catch (IOException e) {
e.printStackTrace();
}
finally{
token = null;
}
}
}
I have checked to ensure that this is indeed where the freeze is occurring. Any ideas?
BufferedReader can block on close() because it contains a synchronized block on the lock instance:
synchronized (lock) {
if (in == null)
return;
in.close();
in = null;
cb = null;
}
This means there is another Thread in your program working with the BufferedReader (possibly blocked in a read()) which is holding the lock when you try to close. The solution is to have this other thread release the lock (interrupted if necessary) to allow the close to get the lock then complete.
Not possible. BufferedReader.close() doesn't do anything that blocks. You don't even need it. PrintWriter.close() will close everything. Remove it.
The only operation that can freeze here is closing the PrintWriter, which implies flushing its buffer, and the reason for that must be that the peer is a long way behind reading the output of this program, or isn't reading it at all.

Trouble in understanding the working of try-catch-finally blocks

Please correct me if I'm wrong, but, I believe that the statements in the try block get executed first, then, if any exception occurs, the statements in the finally block get executed and then the statements in the catch block get executed. If no exception occurs, then the statements in the finally block are executed once the statements in the try block are executed and the statements in the catch block are skipped.
If my above conception is not mistaken, then I don't understand why this piece of code doesn't work:
// sock is an object of the class Socket
public void run() {
try {
in = sock.getInputStream();
scan = new Scanner(in);
out = sock.getOutputStream();
pw = new PrintWriter(out);
} catch (IOException e) {
e.printStackTrace();
} finally {
sock.close();
}
}
It still says that I need to surround the statement in the finally block with try-catch.
No! the statements in the try block are executed first. Then if any exceptions occurs then the catch block statements are executed. And finally block is executed lastly. finally block gets executed even if an exception occurs in the try block. In other words if no exception occurs then first the try block is executed and then the finally block is executed.
In general If your catch block can catch the Exception thrown by the try block.
try -> finally (If No Exception)
try -> catch -> finally (If Exception)
The statements within the catch block are executed whenever an exception is encountered (which can be caught by the listed catch blocks). The statements within the finally block will always get executed, whether or not an exception was thrown within the try block.
Your sock.close(); statement could potentially throw an IOException, so either you should have another try-catch block wrapping the inner try-catch or add a throws declaration to your run() method (and the caller of the method can have a try-catch block surrounding the call).
EDIT (as per comment):
Statements within catch get executed first, then the statements within finally.

Try With Resources vs Try-Catch [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.

How much code to put in try-catch block [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Is there a "best practice" for how much code to put inside a try/catch block?
I have posted 3 different scenarios below.
I did not include behavior in each catch block and i did not include the finally block. This was to improve readability for viewers. Assume each catch does something differently. And assume the finally will be closing the stream. Just trying to create an easy to read example for future readers.
Control, no try/catch.
Code with 1 try/catch for each place needed.
Code with only 1 try/catch surrounding whole code block.
What is generally accepted as the best practice and why?
Scenario 1
Code without try/catch, just for control.
BufferedReader bufferedReader = new BufferedReader(new FileReader("somepath"));
String line;
while ((line = bufferedReader.readLine()) != null) {
Object object = new Object();
this.doSomething(object);
}
bufferedReader.close();
Scenario 2
Code with a try/catch block for each individual place needed.
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader("somepath"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String line;
try {
while ((line = bufferedReader.readLine()) != null) {
Object object = new Object();
this.doSomething(object);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
Scenario 3
Code with 1 try/catch surrounding the whole block of code.
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader("somepath"));
String line;
while ((line = bufferedReader.readLine()) != null) {
Object object = new Object();
this.doSomething(object);
}
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You should scope your try/catches based on the following criteria:
do you need to do different things based on where the exception came from?
do you need to do different things based on which exception was thrown?
what code needs to be skipped (aka is "invalid") when a given exception is thrown?
answering these questions will enable you to determine the appropriate scope for any try/catch block.
I'd put as little in the try-catch as possible.
This allows you to very easily move pieces of code into separate methods which is a good coding practice (obeying single responsibility principle; see the book "Clean Code: A Handbook of Agile Software Craftsmanship" by Robert C. Martin).
Another advantage is that you can quickly identify which code actually can throw an exception.
Scenario 2 seems a bit extreme though, and since the method is pretty small, Scenario 3 seems like the best choice.
However, you need to have your "close" statement in a finally block.
This is a matter of opinion. I've seen each of these patterns a lot.
Pattern 1 is only good when your method can throw the excpetions and have something up the caller chain handle that. That is often desireable. However, since the close call is not in a finally block, it might not be called. At least, use a try-finally block.
Pattern 2 isn't good, since if the first try-catch block handles an exception, the rest of the method is useless.
Pattern 3 is okay, but not great, as printing stack traces hides the fact that the operation failed. What will the caller do if it thinks the operation occurred when it didn't. Also, the closes might not have happened, which can lead to program failure.
In pseudo code, this variant of pattern 3 is better:
Declare Streams, connections, etc.
try
Initialize streams, connections, etc,
Do work.
catch (optional)
Catch and handle exceptions.
Do not simply log and ignore.
finally
Close connections and streams in reverse order.
Remember, closing these objects can throw,
so catch exceptions the close operation throws.
End.
If you are using Java 7, use try-with-resources:
try (BufferedReader bufferedReader = new BufferedReader(new FileReader("somepath"))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
Object object = new Object();
this.doSomething(object);
}
}
Have IOExceptions bubble up to the caller.
You should go with the third scenario.
If the bufferedReader hits an exception then on creation in the second scenario then it you try to readLine() on it, it will hit another exception. No point in raising multiple exceptions for the same problem.
You should also close your bufferedReader in the finally block.
BufferedReader bufferedReader;
try {
bufferedReader = new BufferedReader(new FileReader("somepath"));
String line;
while ((line = bufferedReader.readLine()) != null) {
Object object = new Object();
this.doSomething(object);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null)
bufferedReader.close();
}
I consider an Exception being an uncoditionally returned result type. So when I work with try-catch sections, I'm trying to answer questions
Should I handle an unexpected result here or should I propagate it on a higher level?
Which unexpected results should I handle?
How to handle them?
In 95% of the cases I don't go further than the first point, so I just propagate the errors.
For file processing I use try-with-resources an re-throw the IOException with throw new RuntimeException(e).
I think it's similar with how much code to put in method. Try to write try/catch/finally which takes no more than one screen. I want to say it's not a problem to wrap entire method body into try{} block, but you should separate this code into several methods if it became too long.
You example with one try/catch each doesn't make sense because you just print a stack trace and continue - knowing already that it will be a failure. You might as well try/catch the whole lot, or add throws SomeException to the method signature and let the calling method decide what went wrong.
Also, don't worry about squeezing too much inside a try/catch. You can always extract that code into another method. Readability is one of the single most important aspects of programming.
The third option is certainly best. You don't want your try/catch block to become unwieldy, but in this example, it is short enough that you do not need to divide it as you have done in your second option.
Not scenario 2. If the FileReader or BufferedReader constructor throws, then bufferedReader will be null but the next try/catch will still execute. Therefore you'll get an (uncaught) exception at bufferedReader.readLine -- a NullPointerException. Between scenarios 1 and 3, I generally like 3 more because it doesn't require the caller to catch. BTW, you don't need to catch FileNotFoundException explicitly, because it inherits from IOException and therefore that catch block will catch both.
jtahlborn already has the correct answer.
Unfortunately sometimes, proper exception handling can be pretty bloated.
One should be ready to deal with it, if required.
Another possible scenario are nested try-catch blocks.
Consider:
BufferedReader bufferedReader = new BufferedReader(new FileReader("somepath"));
try {
String line;
while ((line = bufferedReader.readLine()) != null) {
Object object = new Object();
try {
this.doSomething(object);
} catch (InvalidArgumentException iae) {
throw new RuntimeErrorException("Failed to process line " + line + ", iae);
} catch (ParserWarning e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
bufferedReader.close();
}

Categories