这个问题在这里已有答案:
我看了一个解释投掷和投掷的视频如下:
抛出 - 用于将异常委托/传递给调用方法。
class test{
void child() throws filenotfoundException{
//////## this method passes the exception to its caller which is main method
File f = new File("abc")
}
public static void main(String[] args) throws filenotfoundException{
//////##this main method passes the exception to its caller which is JVM
}
}
所以在上面的例子中,如果文件'abc'不存在,并且在child方法中没有使用try catch处理异常,则子方法会将异常传递给main方法。
由于main方法不使用try catch处理异常,因此它还会将异常抛出或传递给其调用方法JVM。
这是对的吗?
抛出 - JVM只了解拾取预定义异常的逻辑。因此,应使用new Exception
手动创建所有用户定义的异常,然后使用throw
关键字将其传递给JVM。
它也是对的吗?
解释是有缺陷的。首先,写的child()不会抛出任何东西。到目前为止,找不到文件不是例外,除非您尝试打开文件进行输入,否则不会发生。
但是,从你的代码中,child()可能抛出异常,main()也是如此。孩子没有,但它的定义可能。
扔你是如何实际的,抛出异常。像这样:
void child() throws FileNotFoundException {
File f("garbage");
if (!f.exists()) {
throw new FileNotFoundException("the world is clean as garbage does not exist");
}
}
你的main()没有try / catch块,但它可以:
void main() {
try {
child();
}
catch (FileNotFoundException e) {
// Oh no!
}
}
throws
用于方法签名,告诉大家“是的,这种方法抛出一个X型的Exception
,请小心”,而throw
用于实际启动这个Exception
并中止函数的执行。
是的,取决于异常,如果你抓住它,它可能会一直冒泡到JVM。然而,一些Exceptions
不会导致执行中止。这些被称为RuntimeException
s。程序员可以决定使用try / catch块来处理它们。 RuntimeException
s不需要在函数签名中声明。