001package org.unix4j.command; 002 003import org.unix4j.io.FileInput; 004import org.unix4j.io.Input; 005 006/** 007 * An exception thrown when a command terminates with an error; in Unix, the 008 * command would return a value different from zero. Note that the Java VM does 009 * NOT terminate and exit if such an exception occurs. 010 */ 011public class ExitValueException extends RuntimeException { 012 013 private static final long serialVersionUID = 2153738224794893827L; 014 015 private final int exitValue; 016 private Input input; 017 018 /** 019 * Constructor with message and non-zero exit value. 020 * 021 * @param message 022 * the error message 023 * @param exitValue 024 * the exit value, must be different from zero 025 * @throws IllegalArgumentException 026 * if {@code exitValue==0} 027 */ 028 public ExitValueException(String message, int exitValue) { 029 super(message); 030 if (exitValue == 0) { 031 throw new IllegalArgumentException("exit value must be a non-zero value"); 032 } 033 this.exitValue = exitValue; 034 } 035 036 /** 037 * Constructor with message, a non-zero exit value and a causing exception. 038 * 039 * @param message 040 * the error message 041 * @param exitValue 042 * the exit value, must be different from zero 043 * @param cause 044 * the exception that caused the error termination of the command 045 * @throws IllegalArgumentException 046 * if {@code exitValue==0} 047 */ 048 public ExitValueException(String message, int exitValue, Throwable cause) { 049 super(message, cause); 050 if (exitValue == 0) { 051 throw new IllegalArgumentException("exit value must be a non-zero value"); 052 } 053 this.exitValue = exitValue; 054 } 055 056 /** 057 * Returns the exit value, an int value or error code different from zero 058 * that was passed to the constructor of this exception. 059 * 060 * @return the non-zero exit or error code value 061 */ 062 public int getExitValue() { 063 return exitValue; 064 } 065 066 @Override 067 public String getMessage() { 068 if (input == null) { 069 return super.getMessage(); 070 } 071 return super.getMessage() + "[input:" + (input instanceof FileInput ? ((FileInput) input).getFileInfo() : input.toString()) + "]"; 072 } 073 074 /** 075 * Sets the input source that was causing this exception, for instance an 076 * input file that was passed to a command. 077 * 078 * @param input 079 * the input source or file that was causing the exception 080 */ 081 public void setInput(Input input) { 082 this.input = input; 083 } 084 085 /** 086 * Returns the input source that was causing this exception, for instance an 087 * input file that was passed to a command. Returns null if it is unknown. 088 * 089 * @return the input source or file that was causing the exception, or null 090 * if it is not known 091 */ 092 public Input getInput() { 093 return input; 094 } 095}