Page 1 of 2 12 LastLast
Results 1 to 20 of 24
  1. #1
    iliyapolak is offline Member
    Join Date
    Jan 2012
    Posts
    14
    Rep Power
    0

    Default Method for calculation Cauchy Inequality with fully implemented handler

    Hello guys!
    I would like to post my method for calculating Cauchy Inequality.Inside catch clause i implemented do-while loop as a handler to handle null values passed to a method.Need your opinion on handler implementation.

    Thank you.
    Java Code:
     public static double cauchyInequality(double value,double value2) throws IllegalArgumentException , ArithmeticException  {
    
                   
                   double a = value;
                   double b = value2;
                   
                   double left_term;
                   double right_term = 1;
                   double num1=a;
                   double num2=b;
                   double left_sum = 1;
                   double right_product = 1;
                   double left_product = 1;
                   double difference;
                   
                   try {
                       
                       if (num1 == 0 || num1 <-1)
                           throw new IllegalArgumentException("first parameter must be greater than 0");
                   else if (num2 == 0 || num2 <-1)
                       throw new ArithmeticException("second parameter can not be 0");
               
                   }catch (IllegalArgumentException e)    {
                       e.printStackTrace(System.out);
                       do {  // handler implementation starts here
                             
                             ++num1;
                             ++num2;
                             
                            left_sum+= num1*num2;
                            left_term = Math.pow(left_sum, 2.0);
                            
                            left_product+= Math.pow(num1, 2.0);
                            right_product+=Math.pow(num2, 2.0);
                            right_term = left_product*right_product;
                            
                            difference = left_term-right_term;
                             
                            System.out.println("num1 " + num1 + "num2 " + num2 + "left_sum " + left_sum + " difference " + difference + "right term  "+ right_term + " left term " + left_term);
                             
                         } while (left_term<10000 && right_term<10000);
               
                   
                       
                       for(StackTraceElement element : e.getStackTrace()){
                         System.out.println(  element.getLineNumber()+ " " + element.getMethodName() + " " + element.getClassName() + " ");
                       }
                   } catch(ArithmeticException e) {
                       e.printStackTrace(System.out);
                    
                       
                       for (StackTraceElement element : e.getStackTrace()){
                           System.out.println(element.getLineNumber() + " " + element.getMethodName()+ " " + element.getClassName() + " ");
                       }
                   }
               
                         do {
                             
                             ++num1;
                             ++num2;
                             
                            left_sum+= num1*num2;
                            left_term = Math.pow(left_sum, 2.0);
                            
                            left_product+= Math.pow(num1, 2.0);
                            right_product+=Math.pow(num2, 2.0);
                            right_term = left_product*right_product;
                            
                            difference = left_term-right_term;
                             
                            System.out.println("num1 " + num1 + "num2 " + num2 + "left_sum " + left_sum + " difference " + difference + "right term  "+ right_term + " left term " + left_term);
                             
                         } while (left_term<10000 && right_term<10000);
               
                   return difference;
               }
    Last edited by iliyapolak; 01-11-2012 at 04:01 PM.

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,172
    Rep Power
    20

    Default Re: Method for calculation Cauchy Inequality with fully implemented handler

    WHy are you doing processing inside the catch block like that?
    That sort of implies it's not an exception.
    You shouldn't use exception handling as a means of normal flow control.

  3. #3
    iliyapolak is offline Member
    Join Date
    Jan 2012
    Posts
    14
    Rep Power
    0

    Default Re: Method for calculation Cauchy Inequality with fully implemented handler

    Thank You for your answer.Processing inside catch block is triggered only when one or both of the arguments are 0.
    When I enter values greater than 0 exception is not triggered and normal do-while loop is processed.
    My intention was to implement exception handling inside catch clause in order to reenter do - while loop with default values(not faulty 0's).
    Simply i tried inside catch clause to" repair the code" instead of throwing an exception.

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,172
    Rep Power
    20

    Default Re: Method for calculation Cauchy Inequality with fully implemented handler

    Why use exceptions for that?
    Just stick that code inside the relevant parts of the if statements which are throwing the exceptions.

    This is not what exceptions are for.
    If you have a way of repairing the code, then it's not an exception, especially since this is within the method throwing the exception.

  5. #5
    iliyapolak is offline Member
    Join Date
    Jan 2012
    Posts
    14
    Rep Power
    0

    Default Re: Method for calculation Cauchy Inequality with fully implemented handler

    Yes i could "repair" faulty conditions in if-statements , but i was inspired by Bruce Eckel book " Thinking in Java 4th edition" where he wrote about the correcting code inside catch clause and implementing exception handler which
    can do more than only displaying stack.It was only an experiment

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,172
    Rep Power
    20

    Default Re: Method for calculation Cauchy Inequality with fully implemented handler

    Oh right.
    If it's just an experiment, then OK.

  7. #7
    iliyapolak is offline Member
    Join Date
    Jan 2012
    Posts
    14
    Rep Power
    0

    Default Re: Method for calculation Cauchy Inequality with fully implemented handler

    After writing another Inequality method and experimenting with code inside catch clause method's flow control inside catch block entered some kind of loop throwing exceptions but continued execution until i changed while statement terminating condition.
    You were right catch block is not for flow redirecting and code correction.

  8. #8
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,172
    Rep Power
    20

    Default Re: Method for calculation Cauchy Inequality with fully implemented handler

    I don't know what Bruce says in that edition, but I suspect his idea of correction was a call to a method that throws an illegal argument, and then using the catch to try and correct one of the parameters?

  9. #9
    iliyapolak is offline Member
    Join Date
    Jan 2012
    Posts
    14
    Rep Power
    0

    Default Re: Method for calculation Cauchy Inequality with fully implemented handler

    He was talking about resumption vs termination his idea was when using resumption place try block inside a while loop that keeps reentering the try block until the result is satisfactionary or simply do not throw a exception and instead call a method that fixes the situation.

  10. #10
    iliyapolak is offline Member
    Join Date
    Jan 2012
    Posts
    14
    Rep Power
    0

    Default Re: Method for calculation Cauchy Inequality with fully implemented handler

    Finally tried resumption with outer while loop and try block inside that loop works fine.

  11. #11
    AndreB's Avatar
    AndreB is offline Senior Member
    Join Date
    Dec 2009
    Location
    Stuttgart, Germany
    Posts
    114
    Rep Power
    0

    Default Re: Method for calculation Cauchy Inequality with fully implemented handler

    yes... a really deep interpretation! (not!)

    if you want to make your code less efficient you sure will code you algorithm throwing and catching exceptions! This is the most efficient way to slow down the whole thing. (Use an additional synchronize block in your loop, for additional speed break!)

    The concept of exeptions is not meant for normal code flow ... and not even Bruce (Almighty) could have suggested it.
    You should use exceptions for "known uknowns" (Unknown unknowns and the Rest)
    There you can try and "fix" your "unknown situtation" with a different code
    "There is no foolproof thing; fools are too smart."
    "Why can't you solve my Problem ?"

  12. #12
    iliyapolak is offline Member
    Join Date
    Jan 2012
    Posts
    14
    Rep Power
    0

    Default Re: Method for calculation Cauchy Inequality with fully implemented handler

    AndreB
    It was only an experiment as i stated earlier.Later i used try block with while loop checking constantly for wrong values entered and this works great.I also could have used if-statements with return 0 or handle the wrong values with function call inside catch block(callee(method for calculation Cauchy inequality )returns unexpected result of calculation).

  13. #13
    AndreB's Avatar
    AndreB is offline Senior Member
    Join Date
    Dec 2009
    Location
    Stuttgart, Germany
    Posts
    114
    Rep Power
    0

    Default Re: Method for calculation Cauchy Inequality with fully implemented handler

    not using exceptions makes your code even more readable...

    Java Code:
    public static double cauchyInequality(double value,double value2) {
    		 
            double a = value;
            double b = value2;
             
            double left_term;
            double right_term = 1;
            double num1=a;
            double num2=b;
            double left_sum = 1;
            double right_product = 1;
            double left_product = 1;
            
            // default value is not a number
            double difference = Double.NaN;
            
            if (num1 == 0 || num1 <-1) {
            	// handle wrong inputs here
            } else if (num2 == 0 || num2 <-1) {
            	// handle wrong inputs here
            } else {
            	do {  // handler implementation starts here
                    
                    ++num1;
                    ++num2;
                     
                   left_sum+= num1*num2;
                   left_term = Math.pow(left_sum, 2.0);
                    
                   left_product+= Math.pow(num1, 2.0);
                   right_product+=Math.pow(num2, 2.0);
                   right_term = left_product*right_product;
                    
                   difference = left_term-right_term;
                     
                   System.out.println("num1 " + num1 + "num2 " + num2 + "left_sum " + left_sum + " difference " + difference + "right term  "+ right_term + " left term " + left_term);
                     
                } while (left_term<10000 && right_term<10000);
            }
             
           
            return difference;
        }
    "There is no foolproof thing; fools are too smart."
    "Why can't you solve my Problem ?"

  14. #14
    iliyapolak is offline Member
    Join Date
    Jan 2012
    Posts
    14
    Rep Power
    0

    Default Re: Method for calculation Cauchy Inequality with fully implemented handler

    Andre thanks for your answer , but while reading your post and looking at your corrections of my code i would like to ask you why you are against the using of exceptions?.

  15. #15
    AndreB's Avatar
    AndreB is offline Senior Member
    Join Date
    Dec 2009
    Location
    Stuttgart, Germany
    Posts
    114
    Rep Power
    0

    Default Re: Method for calculation Cauchy Inequality with fully implemented handler

    i'm not against using exceptions.
    exceptions are a very useful concept in the right place.

    using exceptions for code flow is "bad" programming practice

    - exceptions make your code slow, exception handling is a very costly operation
    - you don't throw exceptions only to handle them in the same call procedure (you usally catch exceptions which come from inner functions and you throw exceptions to hint that a parent method should handle them)
    - exceptions are meant to control the "unexpected" (like file handling for example: if you read a file an IOExceptions may occur if you hard disk crashes - that was unexpected!). the rule of thumb here is: exception are a concept to handle unexpected problems (known unknowns) - using exceptions to check for the input for a function is wrong, because you can expect some wrong input and you can handle it with some input check method
    - your code becomes very hard to read if you put exceptions for code flow

    and there are many other major and minor reasons...
    "There is no foolproof thing; fools are too smart."
    "Why can't you solve my Problem ?"

  16. #16
    iliyapolak is offline Member
    Join Date
    Jan 2012
    Posts
    14
    Rep Power
    0

    Default Re: Method for calculation Cauchy Inequality with fully implemented handler

    And what do you think about this code should i only throw an exceptions and do not handle them in the same method or maybe use only if-statement with return 0.





    Java Code:
     public static double limitSin(double value) throws IllegalArgumentException ,ArithmeticException{
    			  
    			  double sine;
    			  double x = value;
    			  double limit = 0;
    			  
    			  
    			  try {
    				  
    				   if (value <0 || value >Math.PI/2)
    					   throw new IllegalArgumentException("argument x must be between 0 and Pi/2 \t" + value);
    				   
    			  }catch(IllegalArgumentException e){
    				  ExceptionLogger(e);
    				  
    				  for(StackTraceElement element : e.getStackTrace()){
    					  System.out.println(element.getLineNumber()+ " " + element.getMethodName()+ " " + element.getClassName() + " ");
    				  }
    			  }
    			  
    			            try {
    			            	
    			            	for(x = value ; x<Math.PI/2;x+=0.001){
    			            		
    			            		if (value <0 || value > Math.PI/2)
    			            			throw new ArithmeticException("argument x must be between x and Pi/2 \t "  +"value passed is \t " + value);
    			            		
    			            		sine = Math.sin(x);
    			            		limit = sine/x;
    			            		
    			            		System.out.printf("%15s %32s %30s %30s\n" ,"sin("+x+")" , "rad("+x+")" , "limit" , "arg x");
    			            		System.out.printf("%.16f %35.16f %35.16f % 25.3f\n" , sine , x , limit , x);
    			            	}
    			            }catch(ArithmeticException e){
    			            	ExceptionLogger(e);
    			            	
    			            	for(StackTraceElement element : e.getStackTrace()){
    			            		System.out.println(element.getLineNumber()+ " " + element.getMethodName()+ " " + element.getClassName() + " ");
    			            	}
    			            }
    			            
    			            return limit;

  17. #17
    AndreB's Avatar
    AndreB is offline Senior Member
    Join Date
    Dec 2009
    Location
    Stuttgart, Germany
    Posts
    114
    Rep Power
    0

    Default Re: Method for calculation Cauchy Inequality with fully implemented handler

    Well...

    there are two ways of solving this:
    i would prefer checking the input values in the caller object before even calling limitSin method

    then your method(s) would look like

    Java Code:
    	public void callerMethod() {
    
    		double value = 0f;
    		//... get input and check it
    		if (value <0 || value >Math.PI/2) {
    			System.out.println("argument x must be between 0 and Pi/2 \t");
    		} else {
    			double result = limitSin(value);
    			if (result == Double.NaN) {
    				// something was wrong with the calculation
    			}
    		}
    	}
    and the function itself would be

    Java Code:
    public static double limitSin(double value) throws IllegalArgumentException ,ArithmeticException{
    
    		double sine;
    		double x = value;
    		double limit = Double.NaN;
    
    		for(x = value ; x<Math.PI/2;x+=0.001){
    
    			sine = Math.sin(x);
    			limit = sine/x;
    
    			System.out.printf("%15s %32s %30s %30s\n" ,"sin("+x+")" , "rad("+x+")" , "limit" , "arg x");
    			System.out.printf("%.16f %35.16f %35.16f % 25.3f\n" , sine , x , limit , x);
    		}
    		
    		return limit;
    	}
    the other way is what you suggested... returning 0. But if zero value is also a valid value you should propably return Double.NaN

    Java Code:
    public static double limitSin(double value) throws IllegalArgumentException ,ArithmeticException{
    
    		double sine;
    		double x = value;
    		double limit = 0;
    
    		if (value <0 || value >Math.PI/2) {
    			return Double.NaN; 
    		} else {
    
    			for(x = value ; x<Math.PI/2;x+=0.001){
    
    				// this can actually never happen because you are already in the else branch
    				// thus the value is already 0 >= value < Math.PI/2
    				// the value also cannot exceed Math.PI/2 because the for loop would exit
    				// when x >= Math.PI/2
    
    				//if (value <0 || value > Math.PI/2)
    				//    throw new ArithmeticException("argument x must be between x and Pi/2 \t "  +"value passed is \t " + value);
    
    				sine = Math.sin(x);
    				limit = sine/x;
    
    				System.out.printf("%15s %32s %30s %30s\n" ,"sin("+x+")" , "rad("+x+")" , "limit" , "arg x");
    				System.out.printf("%.16f %35.16f %35.16f % 25.3f\n" , sine , x , limit , x);
    			}
    		} 
    		return limit;
    	}
    an even shorter way would be:

    Java Code:
    public static double limitSin(double value) throws IllegalArgumentException ,ArithmeticException{
    
    		double sine;
    		double x = value;
    		double limit = Double.NaN;
    
    		if (value >=0) {
    			for(x = value ; x<Math.PI/2;x+=0.001){
    
    				sine = Math.sin(x);
    				limit = sine/x;
    
    				System.out.printf("%15s %32s %30s %30s\n" ,"sin("+x+")" , "rad("+x+")" , "limit" , "arg x");
    				System.out.printf("%.16f %35.16f %35.16f % 25.3f\n" , sine , x , limit , x);
    			}
    		} 
    		return limit;
    	}
    Last edited by AndreB; 01-16-2012 at 09:39 PM.
    "There is no foolproof thing; fools are too smart."
    "Why can't you solve my Problem ?"

  18. #18
    iliyapolak is offline Member
    Join Date
    Jan 2012
    Posts
    14
    Rep Power
    0

    Default Re: Method for calculation Cauchy Inequality with fully implemented handler

    Thanks for your helping hand. I think that i still must pay attention to those subtle details.In my earlier code i only used throw statements and all error handling was done by the callers , but as i'm still learning java i tried to implement exceptions in my code.
    By the way in the code above i did not handle division by zero , but it is unchecked exception and should be handled in the run-time.

  19. #19
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,172
    Rep Power
    20

    Default Re: Method for calculation Cauchy Inequality with fully implemented handler

    Disagree.
    iliyapolak's example above is a classic example of where exceptions should be applied.

    It's a static helper method.
    Having the calling method's check that the parameters they are supplying are correct (and therefore having the method assume the parameters are correct) strikes me as slightly optimistic.
    Returning 0 as an error signal is a definite code smell as it requires the calling code to interpret that value as an error.

    This should throw an IllegalArgument (or similar), though not quite as written in iliya's code.

  20. #20
    AndreB's Avatar
    AndreB is offline Senior Member
    Join Date
    Dec 2009
    Location
    Stuttgart, Germany
    Posts
    114
    Rep Power
    0

    Default Re: Method for calculation Cauchy Inequality with fully implemented handler

    Quote Originally Posted by Tolls View Post
    Disagree.
    iliyapolak's example above is a classic example of where exceptions should be applied.

    It's a static helper method.
    Having the calling method's check that the parameters they are supplying are correct (and therefore having the method assume the parameters are correct) strikes me as slightly optimistic.
    What makes you think so? Why should execeptions be used in this particular example?

    To my best knowledge defensive programming (Defensive programming - Wikipedia, the free encyclopedia) is a good programming practice! I don't see any optimism here ;-)

    Quote Originally Posted by Tolls View Post
    Returning 0 as an error signal is a definite code smell as it requires the calling code to interpret that value as an error.
    If you look closely into the code, i do not return a "0" value. In the examples above I use Double.NaN as return value for calculations which is actually also a standard behaviour for bad calculations in java.

    It would be nice, if you would provide an example of how you would use exceptions in that particular example.
    "There is no foolproof thing; fools are too smart."
    "Why can't you solve my Problem ?"

Page 1 of 2 12 LastLast

Similar Threads

  1. Can an Interface have implemented method???
    By pppriyadarshi in forum New To Java
    Replies: 1
    Last Post: 09-10-2011, 07:44 PM
  2. Replies: 3
    Last Post: 04-28-2011, 10:43 PM
  3. Simple calculation method problem.
    By carman12 in forum New To Java
    Replies: 11
    Last Post: 12-29-2010, 02:56 AM
  4. Replies: 14
    Last Post: 09-21-2010, 05:10 PM
  5. A Map implemented with ArrayLists
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-16-2008, 11:29 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •