i have set of error codes in java application. i'm using system.exit(code);
return error codes application external applications. there alternatives of system.exit
using bad practice because may shutdown entire jvm.
i have shared experience in past, , tried engineer out system.exit()
. 1 possibility leave runtimeexception
uncaught , return 1
shell, if want more versatility (and don't want ugly stack-trace polluting output), must have @ least "one" call system.exit()
.
public class splat { public static void main(string[] args) { if (args.length > 0 && "splat".equals(args[0])) throw new runtimeexception("splat"); } }
output:
$ java splat $ echo $? > 0 $ java splat splat > exception in thread "main" java.lang.runtimeexception: splat > @ splat.main(splat.java:9) $ echo $? > 1
my reason doing our organisation started using static analysis results sonar kpi , job numbers down. it's terrible reason doing anything, interesting engineering challenge nonetheless ....
an approach tried throwing specific class of runtimeexception
, exit-code instance variable, , catching @ outer scope. way can sure when murder vm you're @ tail of stack anyway ...
public class splat { public static final class exit extends runtimeexception { private int exitcode; public exit(int exitcode) { this.exitcode = exitcode; } } public static void main(string[] args) { try { wrappedmain(args); } catch (exit e) { system.exit(e.exitcode); } } public static void wrappedmain(string[] args) { if (args.length > 0 && "splat".equals(args[0])) { int code = (args.length > 1) ? integer.parseint(args[1]) : 0; throw new exit(code); } } }
output:
$ java splat $ java splat splat $ echo $? > 0 $ java splat splat 1 $ echo $? > 1 > $ java splat splat 2 $ echo $? > 2 $ java splat splat -1 $ echo $? > 127
there caveats approach of course! bit of odd way exit , unfamiliar constraints scratch head. also, if catch (throwable t)
later on, wont able exit!!! if working in static analysis ci environment should highlighted more grievous violation!
Comments
Post a Comment