Is there possibility that a finally block might not execute? [duplicate] - java

This question already has answers here:
Does a finally block always get executed in Java?
(51 answers)
Closed 2 years ago.
We know that no matter whether an exception is thrown, or caught and handled it, the finally block will get executed, So I was curious that is there any possibility that finally block will not executed.
And if System.exit() is called either in try or catch, then also will the finally gets called?

If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
Source: java.sun.com: Java Tutorial: The finally Block

System.exit() will prevent a finally block from executing.

In the Java documentation:
http://java.sun.com/docs/books/tutorial/essential/exceptions/finally.html
It explains Finally very well.
They do note that if the JVM exits, that the finally block will not be called. Or if a thread that is running the block of code gets killed, the finally block will not be called. In all other cases it will.

One thing I can think of right now is an OutOfMemoryError in which case there is a chance that no further code in your app can be executed.

try {
System.out.println("BEFORE");
System.exit(0);
System.out.println("AFTER");
} finally {
System.out.println("FINALLY");
}
this will give you the output:
BEFORE

System.exit(1); you can use

If some Java Native Interface method segfaults (a library function outside of java but called from there crashes) a finally method will also not be called because the entire JVM stops.
Errors in the JVM itself also result in a crash and prevent everything from continued execution.

the finally clause in the try-catch exception block always executes, irrespective of the occurrence of exception in the normal java program flow. If the execution flow is stopped before the finally clause then the finally block will not be executed.
we can use System.exit(1); before finally block and stop the execution flow of the program.

Another situation that I can think of (that is left out from the other answers) is when an exception is thrown inside a finally block, in that case the finally block will not be "completely" executed.

Related

Why is a try catch statement required? [duplicate]

This question already has answers here:
Why do I need to handle an exception for Thread.sleep()?
(3 answers)
Closed 4 years ago.
Why is a try/catch exception handling statement required in Java for the below line:
TimeUnit.MILLISECONDS.sleep(250);
I just want my code to sleep for 250 milliseconds before executing the next line. Why is a try-catch statement required? I can’t forsee any exceptions with this. The sleep function in python doesn't require a try catch.
The exception I get in the IDE without adding the try catch is:
Error:(124, 40) error: unreported exception InterruptedException; must be caught or declared to be thrown
When I surround it in the try catch as per below it works fine:
try {
TimeUnit.MILLISECONDS.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
You need to catch the exception simply because the thread running (sleeping) might be interrupted and you need to catch the interruption.
From the Oracle description of the InterruptedException
Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity.
Interrupting a thread that is sleeping is a very important part of Java. It provides control when you need to stop an application (or a process) and do not want to be halted from doing so due a thread sleeping. The InterruptException allows developers to catch interrupt attempts and deal with it.
Maybe your beef is with checked exceptions in general.... which is a feature of Java that many people do not like. We can understand your frustration with checked exceptions. You can read up more on checked exceptions in Java via Google.

Finally with callback listeners

So, I have the following code:
try{
....
if(serverResp.isSucces()){
callbackListener.onDataLoaded(serverResp);
}
}catch(Exception e){
//...do whatever I have to
}finally{
urlConnection.disconnect();
}
My question is, when the urlConnection.disconnect is being called? Most of the examples with finally explains when its called in case of return. I understand that case, but here I don't have return but to call to a listener.
In most cases the listener callback triggers a new Activity to start. I would like to be sure, that all my previous connections are closed down!
So the main question is:
When the finally get's called, if there is no return but listener callback?
Is this a proper way to close the urlConnection?
finally is the best place to close resources.
The finally block is executed after the point in which the try/catch blocks are exited. This occurs when:
The end of the try block is reached
The try block is exited in any other way (break out of an outer loop, return, an uncaught exception is thrown, etc.)
An exception is caught and execution reaches the end of the catch block
The thread executing this code is terminated.
The only times that finally may not be executed are described here.
In your case, supposing no exceptions are thrown, your callback will be executed before the connection is closed. The connection will be closed after the callback is complete (via full execution or delegatation to some other thread).
Note that disconnect may only be a safe way to ensure connections are closed in newer version of Java. You would normally attempt to read the entire response and then close the input stream. You can find numerous discussions about this on this site.

Valid Commands That Keep A Finally-block From Executing in Java [duplicate]

This question already has answers here:
Does a finally block always get executed in Java?
(51 answers)
Closed 7 years ago.
So I've been assigned to teach a block on exception handling, and I've run into a question I don't have an answer for. What valid (e.g., don't result in either a compiler, or a run-time, error) commands in Java will keep a finally-block from executing?
A return statement won't do it, but a System.exit(0) statement will. My understanding is that a finally-block would execute no matter what. What (valid) statements will prevent a finally-block from doing so, and why?
Quoting Docs:
If the JVM exits while the try or catch code is being executed,
then the finally block may not execute. Likewise, if the thread
executing the try or catch code is interrupted or killed, the finally
block may not execute even though the application as a whole
continues.
Regarding your example about System.exit(), quoting Docs again
Terminates the currently running Java Virtual Machine. The argument
serves as a status code; by convention, a nonzero status code
indicates abnormal termination.
which means that finally will not be executed.
Simple example:
try {
System.out.println("try");
System.exit(0);
} finally {
System.out.println("finally");
}
The above example will print only try but not finally
To quote Oracle's tutorials:
Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
System.exit will just quite the JVM, thus preventing the finally block from running, as will killing the thread containing that block from another thread. Another edge case is having an infinite loop in the try block, which will simply prevent it from ending, so the finally loop will never be reached.
I see three cases to never reach finally block (or any further instructions in the stack frame):
Sudden thread death (including JVM exit)
stack frame operations
Infinite loop ; whatever it's active (while (true)) or passive (acquiring lock, waiting for notification, etc.)
Only native code (including own JVM mechanisms) is supposed to kill thread or play with stack frames. Fatal system errors are also an option.
However, JVM implementations are free to offer such (undesirable ?) feature across his specific API (ie sun.misc.Unsafe) or via an ugly implementation of Java SE API (ie Thread.destroy)

Java - Will try-with-resources call .close() if the user closes the program unexpectedly? [duplicate]

This question already has answers here:
How does Java's System.exit() work with try/catch/finally blocks? [duplicate]
(6 answers)
Closed 6 years ago.
I'm working on some server code for a program I'm developing and I'm using try-with-resource statements to close the sockets.
try (
ServerSocket serverSocket = new ServerSocket(port);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
) {
out.println("This is the server! Hooray! :D");
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
The problem is, what if the user decides to close the program before the try block finishes? Will the .close() methods be called?
This is on oracle's website:it will be closed regardless of whether the try statement completes normally or abruptly But I'm not sure if that includes if the user just closes the program before the try finishes or just if the program crashes.
Thanks.
Yes/no,
"The try-with-resources statement ensures that each resource is closed at the end of the statement"
This can be found at Oracle
Just think about it as a finally block. The finally will always be executed.
"Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues."
This can be found at Oracle
No it will not.
Runtime.addShutdownHook gives more guarantees if you need them but still not 100% because it will not be called if JVM crashes/someone terminate JVM forcibly from outside.
Best possible solution here it to have wrapper process that starts your Java application, watches over it and does what you need when watched process terminates.
If I understand your question correctly,I think it Wont close. The try block has to gracefully complete or catch some exception in order to close the resource. so it should be a checked exception. I believe if you catch a RuntimeException in your try with resources then the resource will be closed. But it wont close the resource with the thread or JVM crashes for issues like OOM.

Thread.stop() and finally [duplicate]

This question already has answers here:
Are Thread.stop and friends ever safe in Java?
(8 answers)
Closed 7 years ago.
I created a following Class named as ThreadClass (which is a thread as you can see),its structure is something like the following
class SomeTask implements Runnable
{
boolean someCondition=true;
public void run() {
try
{
while(someCondition)
{
//Here goes the Process Code
}
}
catch(Exception errorException)
{
//Catching the Exception
}
finally
{
////I expect that this finally should run every time ,whatever happens in the world
}
}
}
My question is about the finally block and the stop() method
As above class is implementing Runnable, so I can create the object of this class and start a thread of it by calling start() method.I am also aware of the fact that I can stop this thread by using stop() (Yes , I know it is deprecated) method .
What I want to clarify myself is that, if somehow I need to call the stop method on the ThreadClass's object, then can I rely on the finally block to execute even if the thread is stopped by calling stop() as I am doing some important closing things in the finally block.
Thread#stop works by throwing a ThreadDeath exception, it doesn't obliterate the thread instantaneously the way System.exit blows away the JVM. ThreadDeath can even be caught, although that's not a good idea. So try blocks are still relevant.
However, complicating this is that if the thread has stop called on it multiple times then, if the second stop is called when the thread is in a finally block then it could be thrown from the finally block so that the finally block would not complete then. And if the thread's cleanup takes a while then it might be likely that stop could be called more than once on it.
Or even if you only call stop once, if at the time that stop is called the thread happens to be already executing its finally block, then the stop would interfere with completing the finally block.
This is similar to what the technotes on Thread primitive deprecation point out:
1) A thread can throw a ThreadDeath exception almost anywhere. All synchronized methods and blocks would have to be studied in great detail, with this in mind.
2) A thread can throw a second ThreadDeath exception while cleaning up from the first (in the catch or finally clause). Cleanup would have to repeated till it succeeded. The code to ensure this would be quite complex.
So there are some cases that are problematic, it would be very difficult to make sure cleanup gets done properly. James' comment is correct, if at all possible you should use interruption for this kind of thing so that the thread can reliably finish its business.

Categories