EN
Java - return status code from main()
7 points
In this short article, we would like to show how to return the status code from the main function in Java.
Quick solution:
xxxxxxxxxx
1
// put at the end of the main()
2
3
System.exit(statusCode);
4
5
// e.g.
6
System.exit(2);
Program.java
file:
xxxxxxxxxx
1
package example;
2
3
public class Program {
4
5
public static void main(String[] args) {
6
7
System.exit(2); // 0 usually means the program ended successfully
8
// other numbers describe error code
9
// e.g.
10
// here we returned error with code 2
11
}
12
}
Example output:
xxxxxxxxxx
1
Process finished with exit code 2
Hint: in Bash, we can use exit status from program / command and do some decisions,
e.g.
xxxxxxxxxx
1command
2
3if [ $? = 2 ];
4then
5echo "error detected";
6fi
Above code is equivalent to the following c++ / cpp code version:
xxxxxxxxxx
1
using namespace std;
2
3
int main()
4
{
5
return 2; // 0 usually means the program ended successfully
6
// other numbers describe error code
7
// e.g.
8
// here we returned error with code 2
9
}