How does Java's System.exit() work with try/catch/finally blocks?
No. System.exit(0)
doesn't return, and the finally block is not executed.
System.exit(int)
can throw a SecurityException
. If that happens, the finally block will be executed. And since the same principal is calling the same method from the same code base, another SecurityException
is likely to be thrown from the second call.
Here's an example of the second case:
import java.security.Permission;
public class Main
{
public static void main(String... argv)
throws Exception
{
System.setSecurityManager(new SecurityManager() {
@Override
public void checkPermission(Permission perm)
{
/* Allow everything else. */
}
@Override
public void checkExit(int status)
{
/* Don't allow exit with any status code. */
throw new SecurityException();
}
});
System.err.println("I'm dying!");
try {
System.exit(0);
} finally {
System.err.println("I'm not dead yet!");
System.exit(1);
}
}
}
Call return statement or System.exit on try or catch block
What will happen if one calls a return statement or System.exit on try
or catch block ?Will finally block execute?
In the case of a return
, Yes. If you want the gory details, they are specified in JLS section 14.20.2.
(Note that in the JLS terminology, a return
counts as an abrupt termination. But that doesn't matter, because when you analyse the spec carefully, you will see that the finally
gets executed for both normal and abrupt terminations.)
In the case of a System.exit()
, No. The call to the exit
method never returns, and it doesn't throw an exception either. Therefore the "enclosing" finally
clauses for the thread never get executed.
(In JLS parlance, the exit()
call doesn't "terminate" at all. It conceptually the same as a method going into an infinite loop that (magically) doesn't use any CPU time. All of the activity associated with JVM shutdown happens on other threads.)
Should I use System.exit(1) when catching an application-stopping Exception?
If you expect someone else to run your program, and they rely on the process status code to know if your program has succeeded or failed, then you should use System.exit(1);
http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#exit%28int%29
Terminates the currently running Java Virtual Machine. The argument
serves as a status code; by convention, a nonzero status code
indicates abnormal termination.
Does a finally block always get executed in Java?
Yes, finally
will be called after the execution of the try
or catch
code blocks.
The only times finally
won't be called are:
- If you invoke
System.exit()
- If you invoke
Runtime.getRuntime().halt(exitStatus)
- If the JVM crashes first
- If the JVM reaches an infinite loop (or some other non-interruptable, non-terminating statement) in the
try
orcatch
block - If the OS forcibly terminates the JVM process; e.g.,
kill -9 <pid>
on UNIX - If the host system dies; e.g., power failure, hardware error, OS panic, et cetera
- If the
finally
block is going to be executed by a daemon thread and all other non-daemon threads exit beforefinally
is called
Does a finally block always get executed in Java?
Yes, finally
will be called after the execution of the try
or catch
code blocks.
The only times finally
won't be called are:
- If you invoke
System.exit()
- If you invoke
Runtime.getRuntime().halt(exitStatus)
- If the JVM crashes first
- If the JVM reaches an infinite loop (or some other non-interruptable, non-terminating statement) in the
try
orcatch
block - If the OS forcibly terminates the JVM process; e.g.,
kill -9 <pid>
on UNIX - If the host system dies; e.g., power failure, hardware error, OS panic, et cetera
- If the
finally
block is going to be executed by a daemon thread and all other non-daemon threads exit beforefinally
is called
Try-catch-finally in java
The only time a finally
block will not be executed is when you call exit()
before finally
is reached. The exit()
call will shutdown the JVM, so no subsequent line of code will be run.
EDIT: This is not entirely correct. See the comments below for additional information.
Related Topics
What Does It Mean: the Serializable Class Does Not Declare a Static Final Serialversionuid Field
How to Call a Method with a Separate Thread in Java
Adding Up Bigdecimals Using Streams
Differencebetween Class.This and This in Java
A Regex to Match a Substring That Isn't Followed by a Certain Other Substring
How to Get the File Name from a String Containing the Absolute File Path
How to Disable Jsessionid in Tomcat Servlet
How to Combine Two Hashmap Objects Containing the Same Types
Easy Way of Running the Same Junit Test Over and Over
Try-Catch-Finally-Return Clarification
Why Java.Util.Optional Is Not Serializable, How to Serialize the Object with Such Fields
How to Properly Express Jpql "Join Fetch" with "Where" Clause as JPA 2 Criteriaquery
Why Does Int Num = Integer.Getinteger("123") Throw Nullpointerexception
Java.Io.Ioexception: Mark/Reset Not Supported
Merge (Concat) Multiple JSONobjects in Java
Trying to Read from the Console in Java
Run Java Application at Windows Startup
Error: Servlet Jar Not Loaded... Offending Class: Javax/Servlet/Servlet.Class