简体   繁体   中英

Java How to “Override” a catch block

I have a method. This method has a catch block.

// 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

// 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. 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:

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 . Take a look at Lino's answer for possible workarounds.


Java purists will notice that you can simply do 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 :)

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. 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 :

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

Then your anotherFunction() catch block will be executed.

You can learn more from here: The Java Tutorials

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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