Java异常帮助
有人可以向我解释一下以下代码中的抛出异常
部分吗?
public static void main(String args[]) throws Exception {
//do something exciting...
}
先感谢您。
Can someone please explain to me the throws Exception
part in the following code?
public static void main(String args[]) throws Exception {
//do something exciting...
}
Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这意味着函数
main(String[])
可以抛出Exception
的任何子类型。在Java中,方法抛出的所有异常(除了RunTimeException
)都必须显式声明。这意味着每个使用 方法
main(String[])
都必须小心(try
,catch
)Exception
,或者也将自身声明为抛出异常
。it means the function
main(String[])
can throw any sub-type ofException
. in Java, all exceptions thrown by a method(exceptRunTimeException
) must be explicitly declared.that means every method using
main(String[])
will have to take care (try
,catch
)Exception
, or declare itself asthrowing Exception
as well.异常是 Java 在发生意外情况时采取行动的一种方式。例如,如果您想从文件中读取/写入文件,则必须处理文件出现问题时将抛出的
IOException
。用一个小例子向您解释这一点:
让我们采用一个名为
method1()
的方法,该方法会引发异常:它可以通过两种方式使用。第一种使用
method2()
的方法只会把烫手山芋进一步扔下去:第二种使用
method3()
的方法将处理该异常。有关异常的更多信息,http://download.oracle.com/javase/tutorial/ Essential/Exceptions/ 应该有帮助。
编辑
假设我们要返回此数组中某个值的包含内容(即输入数字的平方):
int[] squares = {0, 1, 4, 9, 16, 25};
或0
如果数字(输入
)太大。行人编程:
例外大师编程:
第二个示例更清晰,因为您还可以在此之后添加另一个块(然后再添加另一个块),以便解决每个可能的问题。例如,您可以在末尾添加以下内容:
Exceptions are a way Java uses to act when something unexpected happened. For example, if you want to read/write from/to a file, you have to handle
IOException
that will be thrown if there is a problem with the file.A little example to explain that to you:
Let's take a method called
method1()
that throws an exception:It can be used in two ways. The first way with
method2()
will simply toss the hot potatoe further:The second way with
method3()
will take care of that exception.For more information about exceptions, http://download.oracle.com/javase/tutorial/essential/exceptions/ should help.
EDIT
Let's say we want to return the containt of a value in this array (which is the square of the entered number):
int[] squares = {0, 1, 4, 9, 16, 25};
or0
if the number (input
) is too big.Pedestrian Programming:
Exception Guru Programming:
The second example is cleaner, for you can also add another block (and another again) after that, so that every possible problem is fixed. For example, you can add this at the end: