This question already has answers here:
Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java
(12 answers)
Closed 7 years ago.
Can any one share to me difference between System.exit(0) and System.exit(-1) it is helpful if you explain with example.
It's just the difference in terms of the exit code of the process. So if anything was going to take action based on the exit code (where 0 is typically success, and non-zero usually indicates an error) you can control what they see.
As an example, take this tiny Java program, which uses the number of command line arguments as the exit code:
public class Test {
public static void main(String[] args) throws Exception {
System.exit(args.length);
}
}
Now running it from a bash shell, where && means "execute the second command if the first one is successful" we can have:
~ $ java Test && echo Success!
Success!
~ $ java Test boom && echo Success!
System.exit(0) means it is a normal exit from a program.But System.exit(-1) means the exit may be due to some error. Any number other that zero means abnormal exit.
The parameter of System.exit(int) is the return value of your program, which can be evaluated in batch jobs (usually for console programs). By convention, every value other than 0 inidaces that something went wrong.
If you run your Java program in Linux/Unix you can examine the result using echo $? command. This is why it is important to call System.exit(0) (this is done for you if you don't) if everything is fine and System.exit(non-zero) otherwise.
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
Here i am getting this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
System.out.println(input);
while(true){
if(args[0].equals("k")){
System.out.println("k");
}
}
}
You need run the code on cmd as java MyProgram abc xyz then args will contain ["abc", "xyz"].Maybe you are not doing that right now and therefore getting the error.
You need to provide Command Line Arguments like so:
java MyClass k foo bar
These arguments are passed to the array args[] which will then contain {"k", "foo", "bar"}
Therefore args.length will be 3 and args[0] will be k
If you are executing through IDE and not setting arguments OR not passing command line arguments while running through cmd, you'll get this error.
But for this program, even if you pass arguments, it will run in infinite loop probably as while condition is always true.
You are executing this java class without arguments. In that case, args[0] does now exist, and thus the Exception with Error message.
You can modify the if in this form:
if(args[0].equals("k") && args.length > 0 )
so you do not get exception with message
Index 0 out of bounds for length 0
Your program is producing output without error, when Running the program with argument "k" produces the infinite look of printing k. For this you need to run command the java printKjavaFile k , or start it from IDE with this argument.
You are doing 2 things at the same time:
ask for user input via stdin, when the program is running already
parsing the args[], which should be given when the program starts to run
and expect they work together. But they are different.
I suppose you run the app like: java MyClass without adding extra args after this. You can:
provide arg k after java MyClass, so args[] becomes a non-empty array
stop trying to use args, but just focus on input, which is the line you read from user input.
I am asking this question particularly for an Expect implementation in Java. However, I would like to know general suggestions as well.
In Expect programming, is it possible to expect exactly what is prompted after spawning a new process?
For example, instead of expecting some pattern or a fixed string, isn't it better to just expect what is prompted. I feel this should be really helpful at times(especially when there's no conditional sending).
Consider the sample java code here that uses JSch and Expect4j java libraries to do ssh and execute list of commands(ls,pwd,mkdir testdir) on the remote machine.
My question here is why is it necessary to specify a pattern for the prompt? Is it not possible it to get the exact prompt from Channel itself and expect it?
I've programmed in "expect" and in "java".
I think you misunderstand what "expect" basically does. It doesn't look for exact items prompted after spawning a new process.
An expect program basically consists of:
Something that reads the terminal
A set of patterns (typically regular expressions), coupled to a blocks of code.
So, when a new process is spawned, there's a loop that looks something like this
while (terminal.hasMoreText()) {
buffered_text += terminal.readInput();
for (Pattern pattern : patterns) {
if (pattern.matches(buffered_text)) {
String match = pattern.getMatch(buffered_text);
bufferedText.removeAllTextBefore(match);
bufferedText.removeText(match);
pattern.executeBlock();
}
}
}
Of course, this is a massive generalization. But it is close enough to illustrate that expect itself doesn't "exactly expect" anything after launching a process. The program provided to the expect interpreter (which primarily consists of patterns and blocks of code to execute when the patterns match) contains the items which the interpreter's loop will use to match the process's output.
This is why you see some pretty odd expect scripts. For example, nearly everyone "expects" "ogin:" instead of "Login:" because there's little consistency on whether the login prompt is upper or lower case.
You don't have to expect anything. You're free to just send commands immediately and indiscriminately.
It's considered good practice to only reply to specific prompts so that you don't accidentally ruin something by saying the wrong thing at the wrong time, but you're entirely free to ignore this.
The main consideration is that while your normal flow might be:
$ create-backup
$ mkdir latest
$ mv backup.tar.gz latest
With no expectations and just blindly writing input, you can end up with this:
$ create-backup
Disk full, cleanup started...
Largest file: precious-family-memories.tar (510MB)
[R]emove, [S]ave, [A]bort
Invalid input: m
Invalid input: k
Invalid input: d
Invalid input: i
Removing file...
$ latest
latest: command not found
$ mv backup.tar.gz latest
whereas a program that expects $ before continuing would just wait and eventually realize that things are not going according to plan.
A few commands are sensitive to timing (e.g. telnet), but other than that you can send commands whenever you want, with or without waiting for anything at all.
I hope to execute a bash script and obtain normal output or error message. I know for C we have erron or perror to get the number of exit code and the corresponding message. Whether or not there is an equivalent for Java. If not, how could we achieve the same task as in C?
If you start your process like this:
Process p = Runtime.getRuntime().exec("<command>");
The the error code is return like this:
int error_code = p.waitFor();
You're confusing things.
The exit status from a process, out to bash, Java or whatever environment started it, is not the same thing as the values of errno, that can be printed by perror(). The latter are errors for individual system calls, which are clearly at a much lower level.
The exit status of a process can be whatever, there's no standard for that since it's usually just pass/fail, the detailed level is typically coverered by the program itself.
See, for instance, the exit status of GNU grep:
Normally, the exit status is 0 if selected lines are found and 1 otherwise. But the exit status is 2 if an error occurred [...].
That's very high-level, and doesn't tell you what error occured inside grep, just that overall, it failed.
I am invoking a java program from a shell script "TC Shell Script" and the java program returns status codes which represent certain conditions.
The return code of the java prgram is captured in the pre-defined status variable of the TC Shell.
The return codes are captured fine.
The problem I'm facing is when the java program returns or terminates with -1 with System.exit(-1) the shell script is getting 255 as the return code.
All positive numbers are captured fine in the shell script only -1 is being read as 255.
How can i solve this.
Return codes from executables are a small positive number. Negative numbers get converted to unsigned. There is no way to get a negative number into the exit code.
If I am running external program(batch file) from java then, What I need to do:
if (process.exitValue() == 0) {//means executed successfully ???
Can't the return value be something else and batch executed successfully.
Is that the only way to check??
I'm a bit confused by your wording, but by convention, [exitValue()](http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Process.html#exitValue()) returns 0 upon a successful execution. This is, as far as I know, the only way to check.
EDIT:
I suppose you could use [getErrorStream()](http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Process.html#getErrorStream()) - I assume it'll be blank if there are no errors in the process...
Pick one from here
You could read the output stream ( or the error stream ) and interpret it
The exit code of the batch process will be defined by that process but generally an exit code of 0 is defined as successful and a non zero value indicates that something went wrong. In your batch file you can set the return code by calling:
EXIT /B %ERROR_CODE%
%ERROR_CODE% is the number that will be returned as the exit code.
On Linux, your program can return any status you want. By convention 0 means success.
For example, if you execute a shell script, the return status will be the return status of the last command executed in your script.
In many programs 0 is is success, negative numbers are errors and positive numbers are warnings. Of course this is just a convention and it all depends on what convention was followed. In most programming languages you can define an exit code for a program and that is what is picked up.
In Java System.exit(n)
In C main is defined as int main(int argc, char* argv[]) and the return from main is the return from the program.