The difference between System.exit(-1) and return

It is the same for a class or system with only a single method, but it is different when there are multiple classes and methods and the calling relationship is complex.
System.exit(-1) means that all programs (methods, classes, etc.) stop and the system stops running.
return only stops this one method, and does not affect the sequential operation of other methods. For example:
void a(){
b();
c();
d();
} where b() is return.c() is System.exit(-1); then
b() will execute, c() will be executed, but d() will not be executed.

System.exit(int status)
public static void exit(int status)
terminates the currently running Java virtual machine. Arguments are used as status codes; by convention, a non-zero status code indicates abnormal termination.

This method calls the exit method in the Runtime class. The method never returns normally.
Calling System.exit(n) is effectively equivalent to calling:

Runtime.getRuntime().exit(n)

Parameters:
status - the exit status.
throws:


SecurityException - if a security manager exists and its checkExit method does not allow exiting with the specified status
Runtime.exit(int status)
Terminates the currently running Java virtual machine by initiating the virtual machine's shutdown sequence. This method never returns normally. A variable can be used as a status code; by convention, a non-zero status code indicates abnormal termination.
The shutdown sequence of a virtual machine consists of two phases. In the first phase, all registered shutdown hooks (if any) are started in some unspecified order, and they are allowed to run concurrently until the end. In the second phase, if exit finalization is enabled, run all uncalled finalizers. Once this phase is complete, the virtual machine is paused.
If this method is called after the virtual machine has started its shutdown sequence, this method will be blocked indefinitely if the shutdown hook is running. If the shutdown hook has finished running, and on-exit finalization is enabled, then this method will halt the virtual machine with the given status code (if the status code is non-zero); otherwise it will block the virtual machine indefinitely .
The System.exit method is a traditional and convenient way to call this method.
Parameters:
status - the termination status. By convention, a non-zero status code indicates abnormal termination. 
Throws: 
SecurityException - if a security manager exists and its checkExit method does not allow the specified state to exist 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325342625&siteId=291194637