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?

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 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) – DThought May 30 '13 at 11:02

3 Answers3

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().

Michael Berry
  • 70,193
  • 21
  • 157
  • 216
1

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

DerMike
  • 15,594
  • 13
  • 50
  • 63
Raedwald
  • 46,613
  • 43
  • 151
  • 237
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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483