简体   繁体   中英

Execute same piece of code in catch clause for all methods in a class

I have a class that has many methods. All the methods throw one exception when data is not ready. In that case, I want to retry the method after a certain interval. So in catch, I need to add retry logic. The same logic i need to add for all methods.

Is there some way/pattern to execute same logic for all catch clause without copy paste

One way I could think of is to write my own Exception class and Throw that exception. And do this retry logic from My Exception class.

Is there any other better way to this?

class MyClass {
    public void method1() {
        try {
            //do some logic
        } catch (Exception e) {
            //retry logic
            //existing exception handling logic
        }
    }

    public void method2() {
        try {
            //do some logic
        } catch (Exception e) {
            //retry logic
            //existing exception handling logic
        }
    }

    public void method3() {
        try {
            //do some logic
        } catch (Exception e) {
            //retry logic
            //existing exception handling logic
        }
    }
}

EDIT :

class MyClass {
public void method1(int a, int b) {
    try {
        //do some logic
    } catch (Exception e) {
        Object args[] = {a,b};
        executeLater("method1",args);
        //retry logic
        //existing exception handling logic
    }
}

public void method2() {
    try {
        //do some logic
    } catch (Exception e) {
        Object args[] = null;
        executeLater("method1",args);
        //retry logic
        //existing exception handling logic
    }
}

public void method3(String abcd, int a) {
    try {
        //do some logic
    } catch (Exception e) {
        Object args[] = {abcd,a};
        executeLater("method1",args);
        //retry logic
        //existing exception handling logic
    }
}

public boolean executeLater(String methodName, Object args[]){
    //Execute given method with the supplied args
    return true;
}
}

Added code that shows what i would be doing in each catch clause

boolean processCompleted=false;

while(!processCompleted){
    try{
        doProcess();
        processCompleted=true;
    }catch(Exception e){
        Thread.sleep(10000);
    }
}

This might give you an idea. It keeps try to call doProcess until it doesn't throw exception. If any exception occurs, waits 10 seconds.

Well, you could extract the whole catch block content to a method and call that one, but this only works if your retry logic is not dependent on the specific method. And it also requires a try-catch in every method.

Instead, use functional programming to shorten it:

public class Playground
{
    public static void main(String[] args)
    {
        new Playground().method2(1, 2);
        new Playground().method1();
    }

    public void method1()
    {
        tryAndTryAgain(() -> {
            // logic 1
            System.out.println("no params");
            throw new RuntimeException();
        });
    }

    public void method2(int a, int b)
    {
        tryAndTryAgain(() -> {
            // logic 2
            System.out.println(a + " " + b);
            throw new RuntimeException();
        });
    }

    public static void tryAndTryAgain(Runnable tryThis)
    {
        try
        {
            tryThis.run();
        }
        catch (Exception e)
        {
            new Timer().schedule(new TimerTask()
            {
                @Override
                public void run()
                {
                    tryAndTryAgain(tryThis);
                }
            }, 1000);
            // existing exception handling logic
        }
    }
}

The exact structure depends on your specfic implementation, but it should give you an idea how to structure it. The benefit is that all those methods can concentrate on the business logic, and the retry logic and exception handling are done in a util method. And that util method doesn't even need to know anything about parameters, methods, or anything, because all the business logic is contained in the Runnable .

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