It seems this is one way to have a return status code from your main.
but I am wondering where does this int go? I tried it on eclipse, But I do not see it on console.
how do I get the status code
public static void main(String[] args){
int status = 123;
System.exit(status);
}
The exit code is usually returned to a script or program that is running your application, for instance, I wrote the following simple java program
class Test {
public static void main(String[] args) {
System.exit(123);
}
}
I then compiled it using javac Test.java
Next I wrote a simple bash script that would run java Test and then print out the exit code like this
#!/bin/bash
java Test
echo $?
And when i run the bash script the numbers 123 are printed to the screen, as $? is the exit code of the last command that was run.
That value is known as the exit status
The exit status or return code of a process in computer programming is
a small number passed from a child process (or callee) to a parent
process (or caller) when it has finished executing a specific
procedure or delegated task.
Here's a little Java test to demonstrate it
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Foo {
public static void main(String[] args) throws Exception {
if (args.length != 0)
System.exit(Integer.parseInt(args[0]));
ProcessBuilder builder = new ProcessBuilder(Arrays.asList("java", "Foo", "42"));
Process process = builder.start();
System.out.println(process .waitFor());
}
}
compile and run this program without any arguments. It will print
42
This java program starts a child process. When that process ends, it returns the value that was passed to it in System.exit(?) to its parent process which it then prints out.
The exit code (status) is returned to the operating system on termination of the JVM so if you were to run it through terminal/command line you would see if the program terminated abnormally.
C:\JavaTools>javac SystemExit.java
C:\JavaTools>java SystemExit
C:\JavaTools>echo %ERRORLEVEL%
123
The exit code will be returned to the OS. Return 0 means the program exits without an error and vice versa.
Return different error code means different causes. The could help the OS(or parent process) find out what's wrong with the program.
Related
I am running java program from shell script. I need to execute next step in same shell script based on if any exception occur in java program or it ran successful.I am aware that java doesn’t run anything. How can we do it in shell script ?
I know that we can print some string in log and grep it to check the status. is there any better way to do this ?
It would be good even if I can get some elegant way to do it using grep.
If a Java program was terminated because of an exception, the JVM will exit with an error status 1, instead of the usual success status 0. For example, this program exits because of a NullPointerException:
shell$ cat Throw.java
public class Throw {
public static void main(String[] args) {
String s = null;
System.out.println(s.length());
}
}
shell$ java Throw 2>/dev/null; echo $?
1
You can use the exit status in a shell if-statement for example. This will print boo:
if java Throw 2>/dev/null ; then
echo woo
else
echo boo
fi
If you want to set an exit code other than 1, use the System.exit(int status) function.
I have a very simple bash script which calls a java program. I need this bash script to write output to stdout if the java program runs successfully or fails.
#!/bin/bash
if java -jar java_program.jar arg1 ; then echo "run:yes"
else echo "run:no"
fi
if my java program returns
java.lang.ArrayIndexOutOfBoundsException
at java.lang.System.arraycopy(Native Method)
at com.redacted.redacted.AdvancedEncryptionStandard.decrypt(AdvancedEncryptionStandard.java:48)
at com.redacted.redacted.App.getStuff(App.java:58)
at com.redacted.redacted.App.main(App.java:27)
My bash script will still return "run:yes". I'm assuming this is because as far as bash is concerned it called the script and it ran. Is there a way for me to decet if the java program actually runs successfully?
Yes, you can. But you must use System.exit(0) from inside your java program to finish the execution and communicate to bash that everything was OK. Just return 1 instead 0 to communicate an error. The response will be stored at $? inside your bash environment to be used at if.
There's another answer on how to use the $? result on bash:
https://unix.stackexchange.com/questions/22726/how-to-conditionally-do-something-if-a-command-succeeded-or-failed
Normally exiting the 'main' method (without explicit exit) will return '0' to the shell. Uncaught exceptions will return status of 1.
javac a
java a
xception in thread "main" java.lang.Exception
at a.main(a.java:4)
echo $?
=> 1
Where a is just
class a {
public static void main(String [] args) throws Exception {
System.out.println("Hello\n") ;
throw new Exception() ;
}
}
On surface, this is a case when the main just catch the exception, print it, and ignore the exception, therefore the calling process return 0
class a {
public static void main(String [] args) {
System.out.println("Hello\n") ;
try {
doSomething() ;
} catch (Exception e) {
e.printStackTrace) ;
} ;
}
}
Few possible approaches: (1) rewrite the main to allow the exception to 'bubble up' and (2) write new main that will execute the old main, and check for success (3) capture stderr, and check for error messages (messy). Otherwise, you are out of luck
I have a fairly simple Java executable jar that runs the main method, checks the availability of some services, and returns (i.e. terminates) normally if the services are up.
The executable jar is run repeatedly as monitor, and upon failure, an alarm is raised in an external alarm and reporting system.
If the services are down, the code throws a RuntimeException and on the command line, the java command throws the exception.
Does this count as a POSIX fail (i.e. return code 1)? Or, do I need to catch the exceptions and explicitly return 1?
Thanks
I don't think that it's guaranteed to return 1, and I'm not even certain it's guaranteed to return a non-zero value. I think your best bet is to catch that Exception and call System.exit(1).
It's not exactly your question, but they seem to have a better grasp of this than I do if you want to read more on those two diffirent approaches: System.exit(num) or throw a RuntimeException from main?
Yes it does. By testing the following code I was able to verify this.
TestDeath.java
public class TestDeath {
public static void main(String[] args) {
throw new RuntimeException("I'm dying");
}
}
JavaProcess.java
public class JavaProcess {
public static void main(String[] args) throws Exception {
ProcessBuilder builder = new ProcessBuilder("java", "TestDeath");
Process process = builder.start();
int exitValue = process.waitFor();
System.out.println("Exit Code: " + exitValue);
}
}
JavaProcess runs the TestDeath class in a separate process and prints the exit code.
Following is the output.
Exit Code: 1
I had compiled the first class by myself and put it in the current directory of the JavaProcess.
Platform
Windows 7 64 bit
Java 1.8.0_91-b14
I have a very simple Java class, that does nothing else but:
public class TestMain {
public static void main(String[] args) {
System.out.println("Running!");
System.exit(1111);
}
}
, packed into a TestOSX.jar file.
While on Windows I can run the above snippet and show that %ERRORLEVEL% has the expected value, I get a different outcome on OS X.
Given test.sh containing:
#!/bin/bash
"/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java" -jar TestOSX.jar
wait $!
updater_exit_val=$?
echo $updater_evit_val
, I always print 0.
Setup: OS X 10.11.1, Oracle Java 8 u60.
What trivial detail am I missing here?
You do not send your java process to the background with &. Thus wait is executed after the java process exits. It can't find the process you try to wait for, because it already exited and giving return code 0 because of that. $? returns the return code of the last command (in your case wait).
You can either remove wait from your script, or you send your java process to the background by adding & at the end.
I'm just starting Java ... again.
I just made a simple program
class first
{
public static void main()
{
System.out.println("Hello!");
}
}
This runs perfectly fine in BlueJ but it gives an error during run-time when running from command prompt.
This is the error
Exception in thread "main" java.lang.NoSuchMethodError: main
It's because I didn't give String args[] in the main parameter list
Till now, I used to give it subconsciously. I know that the string array contains all the parameter values when running but then why is it running in BlueJ?
(BlueJ is a student-friendly Java editor and compiler)
Your program is valid and will compile to the same thing whether you compile from BlueJ or from the command line.
However, blueJ will let you run any static method in a class (so you can test your functions) where as the command line java command will (only) look for a special main method to run. This main method tages a String array with all the command line parameters and your program should look like this even though you don't use these command line parameters:
class first
{
public static void main(String[] args)
{
System.out.println("Hello!");
}
}