我想提出一个错误并终止一个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中,错误引发的最接近的复制是什么?
谢谢
发布于 2015-01-06 01:46:22
IOException属于java.io包,您应该先导入它。它也是一个“检查”异常,这意味着您应该修改main方法,添加throws IOException,或者在方法主体中捕获它。
import java.io.IOException;
public class Example {
public static void main(String [] args) throws IOException {
...
throw new IOException("Please check that...");
}
}我同意@pbabcdefp的观点,您应该使用IllegalArgumentException,它是一个RuntimeException,不需要在代码中显式地处理。
https://stackoverflow.com/questions/27790543
复制相似问题