Java 异常:异常 myException 永远不会在相应的 try 语句主体中抛出
我理解这个错误的想法。但我想我不明白这是如何在调用堆栈中工作的。
文件 Main.java:Function2
public static void main(String[] args) {
try {
Function1();
} catch (myException e) {
System.out.println(e.getMessage());
}
}
public static void Function1() {
Function2();
}
存在于另一个文件中:
File2.java
public void Function2() throws myException {
....
}
因此,通过几次调用(在调用堆栈中),我得到了 Function2,它指定了“抛出 myException”的要求。为什么主函数(错误所针对的地方)无法识别出我抛出了 myException ?
任何关于我的“异常知识”中的“漏洞”所在的指导将不胜感激。
艾蒂,
I understand the idea of this error. But I guess I don't understand how this works down the call stack.
File Main.java:
public static void main(String[] args) {
try {
Function1();
} catch (myException e) {
System.out.println(e.getMessage());
}
}
public static void Function1() {
Function2();
}
Function2 exists in another file:
File2.java
public void Function2() throws myException {
....
}
So through several calls (down the call stack) I have Function2 which specifies the requirement "throws myException". How come the main function (where the error is being directed at) doesn't recognize that I throw myException down the line?
Any guidance in where the 'hole' in my "exception knowledge" lies would be greatly appreciated.
aitee,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
漏洞是
Function2
声明它抛出异常,但Function1
没有。 Java 不会深入挖掘可能的调用层次结构,而是直接按照您在throws
语句中声明的内容进行操作。Function1
没有声明抛出,可能是因为myException
是一个RuntimeException
。The hole is that
Function2
declares that it throws the exception, butFunction1
does not. Java doesn't dig its way through possible call hierarchies, but goes directly by what you declare inthrows
statements.Function1
gets away with not declaring the throw probably becausemyException
is aRuntimeException
.您的问题是
Function1()
没有声明它抛出 myException
- 这意味着应该有 2 个编译错误:一个是关于未捕获或声明异常的错误,以及一个关于捕获未声明的异常的问题。Your problem is that
Function1()
does not declare that itthrows myException
- which means that there should be 2 compile errors: one about the exception not being caught or declared, and one about catching the exception that is not declared.