mercredi 26 juillet 2017

Best design pattern to skip execution of code if one of the child method throws exception

I am using core java to develop a testing framework. In my application I have a parent method which calls ten different child methods, where each method can throw its own exceptions. The requirement is to provide detailed log information about the execution of parent method which contains information like total time taken to execute the method, time taken to execute each child method, log any exceptions etc. I am using multiple try catch finally blocks for this.

My question is, What's the best way to skip the execution of remaining child methods if one of the child method throws an exception? For eg: If method 4 throws an exception, I want to log that exception and go to the end and log the time taken by parent method until then.

I tried using boolean variable initializing it to true at the beginning of parent method. I am checking if the boolean varible is true before executing each child method. Whenever an exception is thrown, I am marking the boolean variable false.

My psuedocode looks like this:

public String parentMethod(){
    boolean execute = true;
    if(execute) {
        try event1; 
        catch(Event1Exception e1)  
            log e1; execute = false; 
        finally log event 1 time taken;
    }
    if(execute) {
        try event2; 
        catch(Event1Exception e2)  
            log e2; execute = false; 
        finally log event 2 time taken;
    }
    and so on ....
    log total time taken;

In my actual code I have about ten different events which throw their own exceptions, sometimes more than one. With this approach, assigning execute = false for each exception caught and then again checking the value of execute seems clunky. Is there a better approach than this, without using any additional plugins?

Aucun commentaire:

Enregistrer un commentaire