@Override
Public class example {
void test {
try {
someMethod(); //This throws TimeoutException
} catch (TimeoutException ex) {
throw new TimeoutException(ex); //It doesn't throw error if I replace this with throw new RuntimeException(ex)
} }
}
上面的示例给出了一个错误,即“抛出新的 TimeoutException(ex)”,因为“java.util.concurrent.TimeoutException 中的 TimeoutException(java.lang.string) 无法应用于 (java.util.concurrent.TimeoutException)” .
但是如果我将其替换为“抛出新的 RuntimeException(ex)”,它不会引发错误;
最佳答案
TimeoutException
没有接受 TimeoutException
作为 TimeoutException(TimeoutException Cause)
或类似形式的参数的构造函数。
您可以改为:
TimeoutException localtoe=new TimeoutException("test failed");
localtoe.initCause(ex);
throw localtoe;
或者同样:
throw new TimeoutException("test failed").initCause(ex);
initCause()
只能调用一次,且仅在构造函数未设置 Cause 时调用。这是一个有趣的小方法,其作用类似于构造函数的事后思考(*)。
将异常包装为异常的原因并没有一定的错误。
假设 testFunction()
连接并执行一些操作。
您可能希望抛出一个异常,其中包含消息“testFunction 中的连接失败”和另一个“testFunction 中的操作失败”,具体取决于失败的子步骤。
但是,如果您不需要提供如此多的详细信息,您可以抛出 ex
或让方法展开而不捕获任何内容。
这是一个小例子:
import java.util.concurrent.TimeoutException;
class Example{
private static void connect() throws TimeoutException {
//Dummy connection that just fails...
throw new TimeoutException("connection failed");
}
private static void process() throws TimeoutException {
try {
connect();
}catch(TimeoutException toe){
TimeoutException toeout=new TimeoutException("process failed because connection failed.");
toeout.initCause(toe);
throw toeout;
}
//Code for when connection succeeds...
}
public static void main (String[] args) throws java.lang.Exception
{
try{
process();
}catch(TimeoutException toe){
System.out.println(toe);
}
}
}
预期输出:
java.util.concurrent.TimeoutException: process failed because connection failed.
(*) initCause()
看起来像是事后的想法,而且有点像。它于 2002 年被添加到 Java 1.4 中。文档讨论了“遗留”构造函数。似乎决定允许将其作为 bolt 固定初始化,而不是将构造函数的数量增加一倍(添加一个带有 Throwable Cause
参数的构造函数)。
这是否是最好的解决方案还有待商榷。
关于java - 我不能抛出特定的异常吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50811521/