问题描述
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
}
}
当我抛出两种类型的异常(Line4中的IOException和Line3中的RunTimeException)时,我发现我的程序不会编译,直到我在第1行和第1行的throws子句中指出IOException第2行。
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.
而如果我反转抛出来表示IOException被抛出,程序会成功编译,如下所示。
Whereas if I reverse "throws" to indicate IOException being thrown, the program does compile successfully as shown below.
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
}
}
/ p>
Why should I always use "throws" for IOException even though RuntimeException is also thrown (Line 3) ?
推荐答案
为什么我总是使用throws作为IOException,即使RuntimeException也被抛出(第3行)因为 IOException
是一个检查异常,应该被处理或声明为抛出。
相反, RuntimeException
是一个未检查的异常。您不需要处理或声明它抛出方法throws子句(这里我的意思是,如果您不处理未检查的异常,它将在语法上是正确的。编译器不会生气)。然而,有一些情况,您需要处理并针对某些未经检查的异常进行处理。
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.
相关帖子:
- JLS - Kinds and Cause of Exceptions
- Oracle Exceptions Tutorial
这篇关于IOException与RuntimeException Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!