2

In the good old days of C you had int main(...) as the entry function and you could call the executable from a batch file and check %errorlevel% in that batch file which would contain the return value.

In java I compile my java application to something.jar and mark a function like public static void main(String[] rawArgs) as the entry point. I then call java -jar something.jar from the batch file. I can even append command line arguments if I want to.

But now I can't check %errorlevel% since my main function is returning a void.

I suppose this is all perfectly logical given that everything is running in a virtual machine and that is the actual executable rather than something.jar.

I can use System.exit(...) to achieve my original aim.

My question is this: Is there a better way of doing this? Killing off the virtual machine seem heavy handed. What if the code runs server side? Am I missing a cute function like Runtime.SetErrorLevel which does what I want?

1
  • 4
    I don't get the point why you don't want to use System.exit(). You want to return a value from a process, the process is a java virtual machine. System.exit() will end the process (the virtual machine that you executed as "java -jar ...") and return the %errorlevel% back to the OS (in a portable way) Commented May 30, 2013 at 11:02

3 Answers 3

3

System.exit() is the correct way to do what you want - a process can only return an error condition when it exits anyway, so what would be the point in specifying that code anywhere else?

Simply use System.exit() with a non zero parameter to indicate the error level - there's no need to look for an alternative way. If you try to work around it you're just going to end up with horrible native hacks that aren't portable yet accomplish the same thing as System.exit().

Sign up to request clarification or add additional context in comments.

2 Comments

This is not exactly generic. What if you want to pass back a String.
stackoverflow.com/a/2340018/495157 redirect java to temp ... > temp.txt set /p VAR=<temp.txt - Not a great experience though. You wait 20 seconds for JVM to shutdown prior to bat resuming control. Things like the Groovy Console are beneficial then if you call repeatedly.
1

Place a call to System.exit() just before the end of your main function.

Comments

0

Declare a native function in java, static native void SetErrorLevel(int level);, generate the JNI headers using javah.exe and implement the function in C which sets the %errorlevel% environment variable in your process.

Then terminate normally.

1 Comment

A very convoluted way of doing what System.exit() does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.