I have written the following class, and demo, in which I used a default exception (InvalidInputException)... I ran it, and it worked. So I tried my own exception, which I cannot get to work. How do I change the exception that is taken to my own (the Invalid TestScore class)?

public class TestScores
{
    private double[] scores;
    
    public TestScores(double [] s)
    {
        scores = new double[s.length];
        
        
        for (int index = 0; index < s.length; index++)
        {
        if (s[index] > 100 || s[index] < 0)
        {
            throw new InvalidTestScore("Error");
        }
            scores[index] = s[index];
    }
    }
    
    public double getTotal()
    {
        double total = 0.0;
        for (double value : scores)
            total += value;
        return total;
    }
    
    public double getAverage()
    {
        return getTotal()/scores.length;
    }
    
    
}
public class TestScoresDemo
{
   public static void main(String[] args)
   {
      
      double[] badScores = {97.5, 66.7, 88.0, 101.0, 99.0 };

      
      double[] goodScores = {97.5, 66.7, 88.0, 100.0, 99.0 };
      
     
      try
      {
         TestScores tBad = new TestScores(badScores);
         
         System.out.println("The average of the bad scores is " +
                            tBad.getAverage());
      }
      catch (InvalidTestScore e)
      {
         System.out.println("Invalid score found.\n" + e.getMessage());
      }
   
      
      try
      {
         TestScores tGood = new TestScores(goodScores);
         System.out.println("The average of the good scores is " +
                            tGood.getAverage());
      }
      catch (InvalidTestScore e)
      {
         System.out.println("Invalid score found.\n" + e.getMessage());
      }
   }
}
public class InvalidTestScore extends Exception
{
    public InvalidTestScore()
    {
        super("Error, Invalid");
    }
    
    public InvalidTestScore(double amount)
    {
        super("Error, invalid: " + amount);
        
    }

}
public class ExTest 
{
    public static void main(String[] args)
    {
        try
        {
            TestScores score = new TestScores (70,70,80,90,100);
        }
        catch (InvalidTestScores e)
        {
            System.out.println(e.getMessage());
        }
    }

}

The constructor needs to declare that it throws that exception.

public TestScores(double[] s) throws InvalidTestScore {

You also need to:
- Use a constructor that actually exists for InvalidTestScore.
- Use an appropriate constructor for TestScores in ExTest.
- Check the spelling of your exception and use the right one.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.