在java中将checked异常作为unchecked抛出,而不是包装



我有以下代码,需要扫描抛出的异常。如果它满足一个特定的条件,我就忽略这个异常。否则我会重新投球。抛出的异常是一个已检查的异常,这意味着重新抛出是困难的部分。包括我必须捕获它,并且操作在一个重写的方法内进行,该方法的基类"方法没有使用throws clause。在重新编程整个庞大的库或将异常包装为RuntimeException(这不是一个选项,因为我们将包装的已检查异常在未来的某个地方(派生类(在其传播过程中被catch子句预期-这是某种信号(之间,我希望能就这样的实现获得一些建议。或者可能只是实现。

/*
* Translated from c++11_7.3.19 AIEDs schemes >${ref[213]:`through}.
* guarantees learning, re-learning and 'un-learning'. programmed intelligence is not
* altered whatsover and is made as root of bias [x:~y]. fetch cycle is omitted.
*/
@Override
public void intelligenceSync()// No throws clause here
{
try {
super.intelligenceSync();
// the throwing culprit.
global_contribution.acceptOrReformState(this);
generateMetaLogicReforms(this);
} catch (Throwable t_) {
if (t_ instanceof Signalx) {
Signalx sx = (Signalx) t_;
// Note how bias inreases propagation speed by ~12.21 >${ref[371]:exp2}.
applyBias(sx);
stopInvalidation(sx);
// check if x neuron is almost proved.
if (sx.neuronSP() > sx.threshold()) {
// We'll find other ways of completing our proofs.
// Note the algorithm is not so complete.
netsync(sx);
while (sx.pushDeeper()) {
sx.enhance(Metrics.COMPLETION.esteem());
sx.suspendSubPathTraversal(Suspender.IN_DREAM_RESOLVE, Handler.NULL_LOGIC);
}
generateSubLogicReforms(sx);
} else {
restore(sx);
continueInvalidation(sx);
// We rethrow.
uncheckedThrow(sx);
// exception thrown
}
} else if (t_ instanceof Signaly) {
// Reforms must be handle explicitly.otherwise RelationalAttender will complain
// .
// ... blah blah blah.
} else {
// We rethrow
uncheckedThrow(t_);
}
//
}
}

如果您想抛出未检查的异常,或者更具体地说是Throwable,您可以使用以下方法。

private static <T extends Throwable> void uncheckedThrow_helper(Throwable e) throws T{
throw (T)e;
}
static void uncheckedThrow(Throwable e){
uncheckedThrow_helper(e);
}

调用该方法不会导致编译检测到任何Unchecked Exception错误。

try{
uncheckedThrow(new Exception());
System.out.println("It doesn't work");
}catch(Exception e){
System.out.println("It works.");
}

输出:

It works.

我需要类似的东西,但我的方法需要一个返回值,这导致我返回null或类似的东西。

因此,我做了一个小的调整:

private static <T extends Throwable> RuntimeException unchecked(Throwable t) throws T {
throw (T) t;
}

该方法现在返回一个RuntimeException,它允许我们";投掷";未检查的异常,它绕过编译器,不再期望返回任何值。

private static String yourIOOperationThatReturnsSomething() {
throw unchecked(new IOException("test"));
}
public static void main(String []args) {
System.out.println(yourIOOperationThatReturnsSomething());
}

运行示例如下:http://tpcg.io/VIC7A6

相关内容

最新更新