0

For instance:- a method to divide

public static void divide( int a, int b) {
return a/b;  // This would throw ArithmeticException / by 0. whenever b ==0;
}

if b is dynamic input and let's say changes with time. and i want to get a value from this function when b is not 0. In such cases, a way to handle all such functions where exceptions are known and could be resolved would be really beneficial.

A more relevant and real time example would be:-

In test automation :- if a function click on a button and fails with NoSuchElementException, then having a check to recover such unwanted sync related exceptions until certain time would be really beneficial.

Maddy
  • 29
  • 6

1 Answers1

0

In code below, you will find following observations:-

  • ArithmeticException due to divide by 0.

  • Retry logic will keep on trying to re-execute same method multiple times until it executes the method without failure or time limit expires.

  • Hard coded change of values to make the failing function pass after certain time and retry logic to resolve the exception and proceed after that.

Thus, you can apply such logic anywhere and over all such unwanted yet known exception prone methods, which have a habit of auto recovery due to various reasons and you wan't to check for valid amount of time before declaring the output as a failure.

In my case, sync issues like- WebDriverException, NoSuchElementException etc. could be easily resolved and will save me a lot of time because of this.

    package javaTest;
    
    
    import java.lang.reflect.Method;
    import java.util.Date;
    import org.openqa.selenium.ie.InternetExplorerDriver;
    
    
    public class ExceptionHandler extends HandleException
    {
    
        public static int divide(int[] test) 
        {
            System.out.println("Calling signature 1.");
            int c = test[0]/test[1];
            System.out.println("Passed");
            return c;
        }
        
        public static int divide(int a , int b) 
        {
            System.out.println("Calling signature 2.");
            int c = a/b;
            System.out.println("Passed");
            return c;
        }
    
        
        public static void main(String[] args) throws Exception
        {
                int[] test = new int[] {2,0};
                
            try
            {
    //          divide(2,0);    // Usage below with comment Code #1
                divide(test);   // Usage below with comment Code #2
            }
            catch (Exception e)
            {
    //          exceptionRecovery(e, 40000,  "javaTest.ExceptionHandler", "divide", new Object[]{2,0} );                //Code #1
                exceptionRecovery(e, 40000,  "javaTest.ExceptionHandler", "divide", new Object[]{new int[] {2,0}} );    //Code #2
            }
        }
        
    }
    
    
    
    
    class HandleException
    {
        
        
        
        @SuppressWarnings("deprecation")
        public static void executeMyMethod(String fullClassName, String methodName, Object[] args) throws Exception
        {
            Class<?> params[]   = new Class[args.length];
                     params     = setClassTypes(args, params) ;
                     
            Class<?> cls        = Class.forName(fullClassName);
            Object _instance    = cls.newInstance();
            
                Method myMethod = cls.getDeclaredMethod(methodName, params);    
                        myMethod.invoke(_instance, args);   
                            
        }
        
        private static Class<?>[] setClassTypes(Object[] args, Class<?> params[])
        {
            for (int i = 0; i < args.length; i++)
            {
                if (args[i] instanceof Integer) 
                    params[i] = Integer.TYPE;
                else if (args[i] instanceof String) 
                    params[i] = String.class;
                else if ( args[i] instanceof InternetExplorerDriver)
                    params[i] = InternetExplorerDriver.class;
                else if (args[i] instanceof int[])
                    params[i] = int[].class;
                else 
                    System.out.println("Please ask developer to include : \'"+args[i].getClass().getSimpleName()+"\' to permitted inputs for paramters");
            }
            
            return params;
        }
    
        
        
        public static void exceptionRecovery(Exception e, int timeOut, String fullClassName, String methodName, Object[] args) throws Exception
        {
            Exception e1            = e;
            final long startTime    = System.currentTimeMillis();
            Date startDate          = new Date();
            final long waitTimer    = startTime+timeOut;
            int counter             = 0; // manually correct exception to get correct result.
            
            while(System.currentTimeMillis()<=waitTimer)
            {
                if(e1.getClass().getSimpleName().equalsIgnoreCase("ArithmeticException"))
                {
                    System.out.println("Excpetion Caught 1.");
                    try {
                        executeMyMethod(fullClassName, methodName, args);
                        String timeTaken = calcTimeDifference(startDate, new Date());
                        System.out.println("Exception Handled in: "+timeTaken+"seconds");
                        return;
                    }catch (Exception ee)   { e1 =  ee;}
                }
                else if(e1.getClass().getSimpleName().equalsIgnoreCase("InvocationTargetException"))
                {
                    System.out.println("Excpetion Caught 2.");
                    try {
                        executeMyMethod(fullClassName, methodName, args);
                        String timeTaken = calcTimeDifference(startDate, new Date());
                        System.out.println("Exception Handled in: "+timeTaken+"seconds");
                        return;
                    }catch (Exception ee)   { e1 =  ee;}
                }
                else if(e1.getClass().getSimpleName().equalsIgnoreCase("NumberFormatException"))
                {
                    System.out.println("Excpetion Caught 3.");
                    try {
                        String timeTaken = calcTimeDifference(startDate, new Date());
                        System.out.println("Exception Handled in: "+timeTaken+"seconds");
                        return;
                    }catch (Exception ee)   { e1 =  ee;}
                }
                else 
                {
                    System.out.println(e1.getClass().getSimpleName());
                        e.printStackTrace();
                        throw new Exception(e);
                }
                Thread.sleep(1000);
                
                // Manual Correction ... to be removed post validation of above code... if working as expected...
                    counter++; 
                    if(counter == 5)
                    {
    //                  args = new Object[] {1,2};  // for input type as normal
                        args = new Object[] {   new int[] {2,3} };
                    }
            }
            String timeTaken = calcTimeDifference(  startDate, new Date()   );
            System.out.println("Unable to recover in target time of :"+timeTaken+"seconds\n");
            e1.printStackTrace();
        }
        
    
    
        private static String calcTimeDifference(Date d1, Date d2)
        {
                    long diffMs = d2.getTime() - d1.getTime();
                    long diffSec = diffMs / 1000;
    //              long min = diffSec / 60;
                    long sec = diffSec % 60;
                    return sec+"";
        }
        
    }

Hakan Dilek
  • 2,178
  • 2
  • 23
  • 35
Maddy
  • 29
  • 6