Search code examples
javaexceptioninfinity

Java Exception Handling for Infinity


I am trying to write a program to equate the value of any number to any power, and I'm suppose to implement exception handling for exponents less than zero which i successfully did and also exception handle for when the value is too large to output i.e. infinity.

heres my power class which contains the function Power :

public class power
{
// instance variables - replace the example below with your own
public static double Power(double base, int exp) throws IllegalArgumentException
{  

    if(exp < 0){

        throw new IllegalArgumentException("Exponent cannot be less than zero");

    }
    else if(exp == 0){
        return 1;

    }


    else{
        return base * Power(base, exp-1);

    }
}

}   

Heres the Test class :

public class powerTest
{
public static void main(String [] args)
{
  double [] base =  {2.0, 3.0, 2.0, 2.0,  4.0 };
  int [] exponent = {10,   9,   -8, 6400, 53};

  for (int i = 0; i < 5; i++) {

     try {
        double result = power.Power(base[i], exponent[i]);
        System.out.println("result " + result);
     }   
     catch (IllegalArgumentException e) {
        System.out.println(e.getMessage());
     }
     catch (ArithmeticException e) {
        System.out.println(e.getMessage());
     }
  }
}
}

heres the output of the test :

result 1024.0
result 19683.0
Exponent cannot be less than zero
result Infinity
result 8.112963841460668E31

my question is how can i get "result infinity" to say something else through ArithmeticException handling something along the lines of "Floating point Overflow"?

thanks in advance.


Solution

  • Not sure if this is what you are looking for, but you can test for infinity/overflow with an if statement as well:

    if( mfloat == Float.POSITIVE_INFINITY ){
    
        // handle infinite case, throw exception, etc.
    }
    

    So in your situation, you would do something like this:

    public static double 
    Power(double base, int exp) throws IllegalArgumentException
    {  
    
        if(exp < 0){
            throw new IllegalArgumentException("Exponent less than zero");
        }
        else if(exp == 0){
            return 1;
        }
        else{
    
            double returnValue = base * Power(base, exp-1);
            if(returnValue == Double.POSITIVE_INFINITY)
                throw new ArithmeticException("Double overflowed");
    
            return returnValue;
    
        }
    }