A simple test case to demonstrate my 2 problems:
public class Numbers {
private static void usage() {
System.err.println("Usage: java " + getClass().getName() + " range");
System.exit(1);
}
public static void main(String[] args) throws IOException {
try {
int range = Integer.parseInt(args[0]);
} catch (Exception e) {
usage();
}
}
}
getClass()
from a static methodArrayIndexOutOfBoundsException
message instead of the usage()
output. Why doesn't catch (Exception e) catch it?1) getClass is a method on the Object type. In static methods there is no object to call the getClass on
2) The exception is caught in your example - I just tested it.
Works for me, exception is caught.
Getting the class name from a static method without referencing the Numbers.class.getName()
is difficult.
But I found this
String className = Thread.currentThread().getStackTrace()[2].getClassName();
System.err.println("Usage: java " + className + " range");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With