有人可以向我解释以下代码中的throws Exception
部分吗?
public static void main(String args[]) throws Exception {
//do something exciting...
}
提前谢谢你。
它表示函数main(String[])
可以抛出任何子类型的Exception
。 在 Java 中,方法(RunTimeException
除外(抛出的所有异常都必须显式声明。
这意味着每个使用main(String[])
的方法都必须注意(try
,catch
(Exception
,或者声明自己是throwing Exception
。
异常是 Java 在发生意外情况时用来采取行动的一种方式。例如,如果要从文件读取/写入文件,则必须处理在文件出现问题时将抛出的IOException
。
举个小例子来向你解释一下:
让我们采用一个名为 method1()
的方法,它抛出异常:
public void method1() throws MyException {
if (/* whatever you want */)
throw new MyException();
}
它可以通过两种方式使用。第一种方式是method2()
简单地进一步抛出烫手山芋:
public void method2() throws MyException {
method1();
}
method3()
的第二种方式将处理该异常。
public void method3() {
try {
method1();
}
catch (MyException exception) {
{
/* Whatever you want. */
}
}
有关异常的详细信息,http://download.oracle.com/javase/tutorial/essential/exceptions/应该会有所帮助。
编辑
假设我们要返回此数组中一个值的包含(这是输入数字的平方(:如果数字(input
(太大,则int[] squares = {0, 1, 4, 9, 16, 25};
或0
。
行人编程:
if (input > squares.length)
return 0;
else
return squares[input];
异常大师编程:
try {
return squares[input];
}
catch (ArrayIndexOutOfBoundException e) {
return 0;
}
第二个示例更干净,因为您还可以在此之后添加另一个块(然后再添加另一个块(,以便修复每个可能的问题。例如,您可以在末尾添加以下内容:
catch (Exception e) { // Any other exception.
System.err.println("Unknown error");
}