【发布时间】:2016-01-10 08:06:04
【问题描述】:
我想在 Java 中抛出一个异常(任何类型),但限制是我不能将“ throws Exception ”添加到我的 main 方法中。所以我尝试了这个:
import java.io.IOException;
class Util
{
@SuppressWarnings("unchecked")
private static <T extends Throwable> void throwException(Throwable exception, Object dummy) throws T
{
throw (T) exception;
}
public static void throwException(Throwable exception)
{
Util.<RuntimeException>throwException(exception, null);
}
}
public class Test
{
public static void met() {
Util.throwException(new IOException("This is an exception!"));
}
public static void main(String[] args)
{
System.out.println("->main");
try {
Test.met();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
此代码有效,但是当我尝试捕获“IOException”时,例如,在 try-catch 块中,它无法编译。编译器告诉我永远不会抛出 IOException。它仅适用于扩展 RuntimeException 的异常。有没有办法解决这个问题?
添加:
import java.io.IOException;
class Util
{
@SuppressWarnings("unchecked")
private static <T extends Throwable> void throwException(Throwable exception, Object dummy) throws T
{
throw (T) exception;
}
public static void throwException(Throwable exception)
{
Util.<RuntimeException>throwException(exception, null);
}
}
public class Test
{
public static void met() { // this method's signature can't be changed
Util.throwException(new IOException("This is an exception!"));
}
public static void main(String[] args)
{
System.out.println("->main");
try {
Test.met();
} catch (IOException e) { // can't be changed and it does not compile right now
System.out.println(e.getMessage());
}
}
}
【问题讨论】:
-
是的:使用应该使用的异常,而不是用肮脏的技巧欺骗编译器。如果一个方法抛出一个 IOException,它应该用
throws声明它。如果您不想要throws,请使用运行时异常。或者使用选择不检查异常的 JVM 语言,例如 Kotlin。 -
我之所以使用它是因为我在无法更改方法签名的特定上下文中需要它...
-
然后使用运行时异常,而不是检查异常。
-
我遇到以下情况:1)我无法更改方法签名 2)我必须让一些已经编写好的“try -catch 块”才能工作。
-
抱歉,这看起来像是一个懒惰的借口。重写需要正确重写的代码:无论如何,这些 catch 块显然不是首先要捕获新的未声明的 IOException。