Java 异常:在相应的 try 语句的主体中永远不会抛出异常 myException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4317643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Exceptions: exception myException is never thrown in body of corresponding try statement
提问by aitee
I understand the idea of this error. But I guess I don't understand how this works down the call stack.
我理解这个错误的想法。但我想我不明白这是如何在调用堆栈中工作的。
File Main.java:
文件 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:
Function2 存在于另一个文件中:
File2.java
文件2.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?
因此,通过几次调用(在调用堆栈中),我有了 Function2,它指定了“throws myException”的要求。为什么 main 函数(错误指向的地方)没有识别出我将 myException 抛出?
Any guidance in where the 'hole' in my "exception knowledge" lies would be greatly appreciated.
任何关于我的“异常知识”中的“漏洞”所在的指导将不胜感激。
aitee,
艾蒂,
采纳答案by Carl Smotricz
The hole is that Function2
declares that it throws the exception, but Function1
does not. Java doesn't dig its way through possible call hierarchies, but goes directly by what you declare in throws
statements.
漏洞是Function2
声明它抛出异常,但Function1
没有。Java 不会挖掘可能的调用层次结构,而是直接按照您在throws
语句中声明的内容进行处理。
Function1
gets away with not declaring the throw probably because myException
is a RuntimeException
.
Function1
可能因为myException
是一个RuntimeException
.
回答by Michael Borgwardt
Your problem is that Function1()
does not declare that it throws 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.
您的问题是Function1()
没有声明它throws myException
- 这意味着应该有 2 个编译错误:一个关于未捕获或声明的异常,另一个关于捕获未声明的异常。