【发布时间】:2015-03-03 15:22:57
【问题描述】:
我想引发一个错误并终止一个 Java 程序,但我很困惑如何去做,因为它似乎与我在 Python 中的做法有着根本的不同。
在 Python 中我会写:
import sys
if len(sys.argv) != 2:
raise IOError("Please check that there are two command line arguments")
这会产生:
Traceback (most recent call last):
File "<pyshell#26>", line 2, in <module>
raise OSError("Please check that there are two command line arguments")
OSError: Please check that there are two command line arguments
这就是我想要的,因为我不想捕捉错误。
在 Java 中,我尝试做类似的事情:
public class Example {
public static void main (String[] args){
int argLength = args.length;
if (argLength != 2) {
throw IOException("Please check that there are two command line arguments");
}
}
}
但是 NetBeans 告诉我它“找不到符号”IOException
我找到了抛出异常的这些答案:
How to throw again IOException in java?
但他们都建议定义全新的类。这是必要的吗?即使 IOException 属于 Throwable 类?
我对 Python 和 Java 之间区别的根本误解阻碍了我。我如何基本上实现我的 python 示例所取得的成就?在 Java 中引发该错误的最接近的复制是什么?
谢谢
【问题讨论】:
-
你不需要定义一个全新的类。扔一个标准的
throw new IllegalArgumentException("Please check..."); -
好的,是的!我希望它是这样简单的。谢谢。
标签: java python error-handling throw