简体   繁体   English

Java如何“覆盖”捕获块

[英]Java How to “Override” a catch block

I have a method. 我有办法 This method has a catch block. 此方法有一个catch块。

// pseudo code
private void function() {
    try {
        // something
    } catch(exception e) {
        // error handling
    }
}

This method is called in another class In one scenario the class is implemented with its own catch block 在另一类中调用此方法。在一种情况下,该类使用其自己的catch块实现。

// pseudo code
private void anotherFunction() {
    try {
        function(); 
    } catch {
        //another catch block
    }

Now I just want to execute the code in the catch block where the function is called and don't call the catch block implemented in the class. 现在,我只想在调用该函数的catch块中执行代码,而不要调用该类中实现的catch块。 Is there a way to do this or should I think about another approach? 有没有办法做到这一点,或者我应该考虑另一种方法吗?

A workaround is to move your logic to another method which doesn't handle that exception, but just passes it upwards eg: 一种解决方法是将您的逻辑移至另一种不处理该异常的方法,而只是将其向上传递,例如:

public void unsafeFunction() throws Exception{
    // something
}

And then call that method from your both classes, where both handle the exception differently: 然后从两个类中调用该方法,这两个类对异常的处理方式不同:

public void function(){
    try {
        unsafeFunction();
    } catch(Exception e){
        // error handling
    }
}

And: 和:

public void anotherFunction(){
    try {
        unsafeFunction();
    } catch(Exception e){
        // other error handling
    }
}

That way you leave what should be done with the exception to the caller. 这样一来,您就可以将调用者的例外情况留给调用者。


Another completly different approach is to use the java.util.function.Consumer interface from Java 8 and accept that in your function , the caller then can just pass the error-handler into it: 另一种完全不同的方法是使用Java 8中的java.util.function.Consumer接口并接受您的function ,然后调用者可以将错误处理程序传递给它:

public void function(Consumer<? super Exception> errorHandler){
    try{
        // something
    } catch(Exception e){
        // delegate to handler
        errorHandler.accept(e);
    }
}

Which can then be used like this: 然后可以这样使用:

public void someFunction(){
    function(e -> {
        // error handling
    });
}

And: 和:

public void anotherFunction(){
    function(e -> {
        // other error handling
    });
}

There must be a reason to catch the exception. 一定有理由捕获异常。 Say that reason can be tested in a separate method: 说原因可以用另一种方法进行测试:

private boolean testCircumstanceThrowingException() {
    if (exceptionalCircumstance) {
        return false;
    } else {
        return true;
    }
}

then you can implement your original function as: 那么您可以将原始功能实现为:

private void functionCatchingException(){
    if (testCircumstanceThrowingException()) {
        //error handling
    }

    function();
}

and

private void anotherFunction() {
    if (testCircumstanceThrowingException()) {
        //error handling
    }

    function();
}

this way, during the normal running of the application, no exceptions are thrown. 这样,在应用程序正常运行期间,不会引发任何异常。 And this is how it should be because exceptions are for exceptional circumstances . 这是应该的,因为例外是针对特殊情况的 If you somehow get to a state where exceptions are expected then something is wrong. 如果您以某种方式进入了预期会出现异常的状态,则说明出现了问题。

You should only rely on excpetions if there is no other way . 如果没有其他方法,则应仅依靠竞争。 For instance, if your specific use of the function cannot test the exceptional circumstance and you're required to use function . 例如,如果您对function特定使用无法测试异常情况,则需要使用function Take a look at Lino's answer for possible workarounds. 查看Lino的答案,以了解可能的解决方法。


Java purists will notice that you can simply do return exceptionalCircumstance; Java纯粹主义者会注意到,您可以简单地return exceptionalCircumstance; but this code was just intended to show that a function that tests for the exceptional circumstance may be required; 但是此代码只是为了表明可能需要测试异常情况的函数; the result may not even be a boolean. 结果甚至可能不是布尔值。

Of course you may now want to rename functionCatchingException :) 当然,您现在可能想要重命名functionCatchingException :)

In your first code snippet: 在您的第一个代码段中:

private void function() {
    try {
        // something
    }
    catch (Exception e) {
        // error handling
        throw e; // rethrow?
    }
}

you basically have two options with Java. Java基本上有两种选择。 You can either swallow the exception, or you can rethrow it. 您可以吞下该异常,也可以将其重新抛出。 If you swallow it, then the caller of this method won't see an exception. 如果吞下它,则此方法的调用者将不会看到异常。 If you rethrow, then the caller would also get an exception. 如果您重新抛出,则调用方也将获得异常。

If neither of these behaviors are what you really want, then you might want to rethink your design. 如果这些行为都不是您真正想要的,那么您可能需要重新考虑您的设计。

You can throw the exception to the caller method using the keyword throw : 您可以使用关键字throw将异常抛出给调用方方法:

private void function(){
    try{
       //something
    } catch(Exception e){
       //error handling
       throw e;
    }
}

Then your anotherFunction() catch block will be executed. 然后您的anotherFunction() catch块将被执行。

You can learn more from here: The Java Tutorials 您可以从这里了解更多信息: Java教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM