我的猜测是,你试图抛出一个异常的子类,而不是由该方法声明作为它可以抛出的异常类型。
以下示例适用
package test.example;
public class ExceptionTest {
public static void main(String[] args) throws Exception{
try {
int value = 1/0;
} catch (Exception e) {
System.out.println("woops the world is going to end");
throw e;
}
}
}
然而这个例子会给出一个错误。在第二个例子中,我简单地捕捉异常不是RuntimeException的
package test.example;
public class ExceptionTest {
public static void main(String[] args) throws RuntimeException{
try {
int value = 1/0;
} catch (Exception e) {
System.out.println("woops the world is going to end");
throw e;
}
}
}
注意,它不会编译,因为我抛出的异常是一个未声明的抛出,即使我做申报的RuntimeException。
是的异常是一个RuntimeException,但编译器不知道。
只是想到了第三个工作实例来向你展示。这一个也适用,因为你抛出相同的类型,你声明。 (注意,唯一的变化是catch块)
package test.example;
public class ExceptionTest {
public static void main(String[] args) throws RuntimeException{
try {
int value = 1/0;
} catch (RuntimeException e) {
System.out.println("woops the world is going to end");
throw e;
}
}
}
您需要了解所有这三个答案之间的差异
来源
2011-05-12 22:31:23
Wes
感谢所有的答案,代码是一个线程,所以我不的run方法中认为我可以抛出异常? – 2011-05-12 22:41:31
[Throw error to calling method!]可能的重复(http://stackoverflow.com/questions/5976764/throw-error-to-calling-method) – McDowell 2011-05-12 22:50:35
我不这么认为,但也许我错了,我真的想知道的是为什么我需要围绕“抛出异常”与try catch。抛出异常时,抛出异常不能抛出异常吗?尝试 { 抛出异常 } 赶上(例外E2) { ... } – 2011-05-12 22:57:35