IOException 与 RuntimeException Java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18416511/
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
IOException vs RuntimeException Java
提问by UnderDog
class Y {
public static void main(String[] args) throws RuntimeException{//Line 1
try {
doSomething();
}
catch (RuntimeException e) {
System.out.println(e);
}
}
static void doSomething() throws RuntimeException{ //Line 2
if (Math.random() > 0.5) throw new RuntimeException(); //Line 3
throw new IOException();//Line 4
}
}
When I throw two types of exception (IOException in Line4 and RunTimeException in Line3), I found that my program does not compile until I indicate "IOException" in my throws clauses in Line 1 & Line 2.
当我抛出两种类型的异常(第 4 行中的 IOException 和第 3 行中的 RunTimeException)时,我发现我的程序无法编译,直到我在第 1 行和第 2 行的 throws 子句中指明“IOException”。
Whereas if I reverse "throws" to indicate IOException being thrown, the program does compile successfully as shown below.
而如果我反转“throws”以指示抛出 IOException,则程序确实编译成功,如下所示。
class Y {
public static void main(String[] args) throws IOException {//Line1
try {
doSomething();
}
catch (RuntimeException e) {
System.out.println(e);
}
}
static void doSomething() throws IOException {//Line 2
if (Math.random() > 0.5) throw new RuntimeException();//Line 3
throw new IOException();//Line 4
}
}
Why should I always use "throws" for IOException even though RuntimeException is also thrown (Line 3) ?
为什么我应该总是对 IOException 使用“throws”,即使 RuntimeException 也被抛出(第 3 行)?
采纳答案by Rohit Jain
Because IOException
is a Checked Exception, which should be either handled or declared to be thrown.
On contrary, RuntimeException
is an Unchecked Exception. You don't need to handle or declare it to be thrown in method throws clause (Here I mean, it would be syntactically correct if you don't handle the unchecked exception. Compiler won't be angry). However there are some situation, where you need to handle and act accordingly for some Unchecked Exception.
因为IOException
是一个检查异常,它应该被处理或声明为抛出。相反,RuntimeException
是一个未经检查的异常。你不需要在方法 throws 子句中处理或声明它被抛出(我的意思是,如果你不处理未经检查的异常,它在语法上是正确的。编译器不会生气)。但是,在某些情况下,您需要针对某些未经检查的异常进行处理并采取相应的行动。
Related Post:
相关帖子:
References:
参考:
回答by svz
The reason is that there are two different types of exceptions in this case. One is a checked
exception which ought to be handled by the programmer and the other one is an unchecked
exception which doesn't require special handling.
原因是在这种情况下有两种不同类型的异常。一个是checked
应该由程序员处理的unchecked
异常,另一个是不需要特殊处理的异常。