一个简单的测试用例来演示我的 2 个问题:
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()
- 如果没有在命令行提供任何参数,我将得到
ArrayIndexOutOfBoundsException
消息而不是usage()
输出。为什么catch (Exception e) 没有捕获到它?
最佳答案
1) getClass 是 Object 类型的方法。在静态方法中,没有对象可以调用 getClass
2) 异常在你的例子中被捕获 - 我刚刚测试过它。
关于java:查找程序名称,解析整数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6703827/