/**
* Title: CmdLine2
* Description: Demo of custom exception
* @author hollingd@cs.rpi.edu
*/
// create our own type of exception
// exceptions are just objects !
class CmdLineException extends Exception {
CmdLineException(){}
CmdLineException(String s) { super(s); }
}
// a class that can convert an array of Strings to
// to an array of integers.
class CmdLineInts {
int x[];
// Constructor with just args, in this case we
// don't care how many are specified on the command line,
// we convert them all
CmdLineInts(String args[] ) throws CmdLineException {
x = new int[args.length];
int i=0;
try {
for (i=0;i<args.length;i++)
x[i] = Integer.parseInt(args[i]);
} catch (NumberFormatException nfe) {
throw new CmdLineException("Invalid argument format: " + args[i]);
} catch (Exception e) {
throw new CmdLineException("Unknown command line error");
}
}
// Constructor with args and number of args.
CmdLineInts(String args[], int num ) throws CmdLineException, Exception {
x = new int[num];
int i=0;
try {
for (i=0;i<num;i++)
x[i] = Integer.parseInt(args[i]);
} catch (NumberFormatException nfe) {
throw new CmdLineException("Invalid argument format: " + args[i]);
} catch (ArrayIndexOutOfBoundsException ae) {
throw new CmdLineException("Not enough args");
} catch (Exception up) {
// here is an example of re-throwing an exception
// (unmodified).
throw up;
}
}
public int []GetInts() {
return(x);
}
}
public class CmdLine2{
public static void main(String[] args) {
int x[];
try {
CmdLineInts c = new CmdLineInts(args);
x = c.GetInts();
// print out the ints.
System.out.print("Args: ");
for (int i=0;i<x.length;i++) {
System.out.print(x[i]+ " ");
}
// just print newline
System.out.println();
} catch (Exception e) {
e.printStackTrace(System.out);
}
// now try but insist on at least 3 ints
try {
CmdLineInts c = new CmdLineInts(args,3);
x = c.GetInts();
// print out the ints.
System.out.print("Args: ");
for (int i=0;i<x.length;i++) {
System.out.print(x[i]+ " ");
}
// just print newline
System.out.println();
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}