Setting exit code in java

Exit codes in Java – System.exit() method

This post will discuss the System exit codes in Java.

The System.exit(int) is the conventional and convenient means to terminate the currently running Java virtual machine by initiating its shutdown sequence. The argument of the exit() method serves as a status code to denotes the termination status. The argument can be either zero or nonzero:

1. Zero

The zero status code should be used when the program execution went fine, i.e., the program is terminated successfully.

2. Non-Zero

A nonzero status code indicates abnormal termination. Java allows us to use different values for different kinds of errors. A nonzero status code can be further positive or negative:

Positive status codes are often used for user-defined codes to indicate a particular exception.

Negative status codes are system generated error codes. They are generated due to some unanticipated exception, system error, or forced termination of the program.

  1. There are no pre-defined constants in Java to indicate SUCCESS and FAILURE messages.
  2. We should always use the proper status codes if our application interact with some tools or the program is called within a script.
  3. System.exit() method internally calls exit() method of the Runtime class. Therefore, the call System.exit(n) is effectively equivalent to the call: Runtime.getRuntime().exit(n) .

That’s all about exit codes in Java.

Average rating 4.47 /5. Vote count: 55

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?

Источник

System.exit(). Какой код выхода использовать?

Что является причиной того, что java программа прекращает любую свою активность и завершает свое выполнение? Основных причин может быть 2 (JLS Секция 12.8):

  • Все потоки, которые не являются демонами, выполнены;
  • Какой то из потоков вызывает метод exit() класса Runtime или же класса System и
    SecurityManager дает добро на выполнение exit().

Именно значение 0 и возвращает JVM в первом, вышеописанном случае при своем завершении.

image

Как это можно проверить?
Тут нам на помощь приходит параметр командной строки ERRORLEVEL, который позволяет получить код выхода программы, которую мы запускали последней.

Как видим со скриншота код выхода равен 0.

Переходим ко второму случаю, с использованием метода exit().

Какие значения можно передавать в метод exit? Исходя из документации:

The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.

Ага, варианта два: либо 0, либо любое ненулевое значение. Второй вариант можем разбить еще на два под варианта: любое отрицательное число и любое положительное число типа int.

Читайте также:  Python install egg module

image

Как видим, родительский процесс снова получил информацию об успешном завершении JVM.

А что же с nonzero значениями? Что, когда и в каком случае передавать?
Тут все просто — никаких требований для nonzero значений нету и следует руководствоваться лишь одним общим правилом:

  1. Возвращаем код выхода со значением >0 в случае, если мы ожидали что что то может случится нехорошее и оно таки случилось, например: некорректные данные в args[], или не удалось найти какой то важный для работы приложения файл, или не удалось подключиться к серверу и тд.
  2. Возвращаем код выхода со значением

И последний вариант: если нам известно, что код выхода дополнительно обрабатывается и дабы не выдумывать значения самому можно позаимствовать значения, которые используются на уровни ОС.
Например, для ОС семейства Windows существует целый список из 15999 кодов: System Error Codes, для семейства Linux свой список: sysexits.h

Источник

Exit Method in Java

Java Course - Mastering the Fundamentals

Jump statements are used to change the flow of a program and transfer control from one point to another point. The break , continue and return statements are the jump statements used in Java.

Along with jump statements, methods like goto() and exit() are used to transfer the control of the program. System.exit() method exits current program by terminating the Java Virtual Machine. Similarly goto with label in Java is used to transfer the control of the program to a particular position in the code.

Introduction

Java has provided a number of inbuilt functions and statements that can control and transfer the flow of programs. Jump statements like break , continue , and return are used in loops and functions. Java does not support goto and has reserved it as a keyword to use in later versions, but instead, it supports label.

  • goto(label) is a control statement used to transfer control to a certain point in the program.
  • goto statement works with the labels which serve as identifiers and are used to a point to a particular position in the code.
  • We can use label name with break statement to break out of a specific outer loop.
  • We can use label name with continue statement to continue execution from a particular point in the code.
  • After the goto(label) statement is executed program starts executing the lines where goto(label) has transferred its control and then subsequent statements are executed.

Explanation:

When the if condition is true , i.e. when j == 2 , break Task; will break out of the outermost loop labelled with Task.

What is exit() Method in Java?

Java provides exit() method to exit the program at any point by terminating running JVM, based on some condition or programming logic. In Java exit() method is in java.lang.System class. This System.exit() method terminates the current JVM running on the system which results in termination of code being executed currently. This method takes status code as an argument.

Uses

  • exit() method is required when there is an abnormal condition and we need to terminate the program immediately.
  • exit() method can be used instead of throwing an exception and providing the user a script that mentions what caused the program to exit abruptly.
  • Another use-case for exit() method in java, is if a programmer wants to terminate the execution of the program in case of wrong inputs.

Syntax of exit() in Java

Parameters of exit() in jJava

System.exit() method takes status as a parameter, these status codes tell about the status of termination. This status code is an integer value and its meanings are as follows:

  • exit(0) — Indicates successful termination
  • exit(1) — Indicates unsuccessful termination
  • exit(-1) — Indicates unsuccessful termination with Exception

Note: Any non-zero value as status code indicates unsuccessful termination.

Return Value for exit() in Java

As the syntax suggests, it is a void method that does not return any value.

Exit a Java Method using System.exit(0)

As mentioned earlier, System.exit(0) method terminates JVM which results in termination of the currently running program too. Status is the single parameter that the method takes. If the status is 0 , it indicates the termination is successful.

Let’s see practical implementations of System.exit(0) method in Java.

Here is a simple program that uses System.exit(0) method to terminate the program based on the condition.

Explanation:

In the above program, an array is being accessed till its index is 4 . Until if condition is false i.e., array index

Once the if condition is true i.e., array index > 4 , JVM will execute statements inside the if condition. Here it will first execute the print statement and when exit(0) method is called it will terminate JVM and program execution.

Let’s see one more example of exit() method in a try-catch-finally block.

Explanation:

The piece of code above is trying to read a file and print a line from it if the file exists. If a file doesn’t exist, the exception is raised and execution will go in catch block and code exits with System.exit(0) method in the catch block.

  • We know, finally block is executed every time irrespective of try-catch blocks are being executed or not. But, in this case, the file is not present so JVM will check the catch block where System.exit(0) method is used that terminates JVM and currently running the program.
  • As the JVM is terminated in the catch block, JVM won’t be able to read the final block hence, the final block will not be executed.

Exit a Java Method using Return

exit() method in java is the simplest way to terminate the program in abnormal conditions. There is one more way to exit the java program using return keyword. return keyword completes execution of the method when used and returns the value from the function. The return keyword can be used to exit any method when it doesn’t return any value.

Let’s see this using an example:

Explanation:

In the above program, SubMethod takes two arguments num1 and num2 , subtracts num2 from num1 giving the result in the answer variable. But it has one condition that states num2 should not be greater than num1 , this condition is implemented using if conditional block.

If this condition is true, it will execute if block which has a return statement. In this case, SubMethod is of void type hence, return doesn’t return any value and in this way exits the function.

Does goto Exist in Java?

No, goto does not exist in Java. Because Java has reserved it for now and may use it in a later version.

In other languages, goto is a control statement used to transfer control to a certain point in the programming. After goto statement is executed program starts executing the lines where goto has transferred its control and then other lines are executed. goto statement works with labels that are identifiers, these labels are used to the state where goto has to transfer the control of execution.

Java does not support goto() method but it supports label. No support for goto method is due to the following reasons:

  1. Goto-ridden code hard to understand and hard to maintain
  2. These labels can be used with nested loops. A combination of break, continue and labels can be used to achieve the functionality of goto() method in Java.
  3. Prohibits compiler optimization

In the above code, the outer label is created for the first for loop. When if the condition is true break outer; statement will go back to first for loop and break the execution.

Conclusion

  • exit() method is used to terminate JVM.
  • Status code other than 0 in exit() method indicates abnormal termination of code.
  • goto does not exist in Java, but it supports labels.
  • It is better to use exception handling or plain return statements to exit a program while execution.
  • System.exit() method suit better for script-based applications or wherever the status codes are interpreted.

Источник

Оцените статью