0

How do you write your own custom exception class.

I'm trying to write my own exception class that throws an InvalidTestScore.

// george beazer
import java.util.Scanner;

public class TestScores{
    public static void main(String[]args){
                int numTests = 0;
                double[] grade = new double[numTests];
                double totGrades = 0;
                double average;   

                Scanner keyboard = new Scanner(System.in);
                System.out.print("How many tests do you have? ");

                numTests = keyboard.nextInt();
                grade = new double[(int) numTests];

                for (int index = 0; index < grade.length; index++){
                        System.out.print("Enter grade for Test " + (index + 1) + ": ");
                        grade[index] = keyboard.nextDouble();        

                        if (grade[index] < 0 || grade[index]> 100){
                                try {
                                  throw new InvalidTestScore();

                                } catch (InvalidTestScore e) 
                                {

                                    e.printStackTrace();

                                }
                        }
                }


                for (int index = 0; index < grade.length; index++){
                        totGrades += grade[index];
                }

                average = totGrades/grade.length;
                System.out.print("The average is: " + average);
        }

}
Kurtis Nusbaum
  • 30,445
  • 13
  • 78
  • 102
user599272
  • 141
  • 1
  • 3
  • 9
  • Why is there so much space between the lines? Much easier to read if condensed (same thing I say for dissertations, but they make us do double-spacing anyway). – Chris Dennett Feb 07 '11 at 22:06
  • possible duplicate of [How can I write an Exception by myself?](http://stackoverflow.com/questions/1070590/how-can-i-write-an-exception-by-myself) – fglez Apr 03 '13 at 15:35

3 Answers3

2

Just extend Exception:

public class InvalidTestScoreException extends Exception {

   public InvalidTestScoreException() {
      super("Invalid test score");
   }

   public InvalidTestScoreException(String message) {
      super(message);
   }

   public InvalidTestScoreException(Throwable throwable) {
      super(throwable);
   }
}

On another note, checked exceptions are very attractive initially. But you should avoid their unnecessary use. Checked exceptions are used to force a programmer to deal with the exceptional condition (which makes the code more reliable since the exceptional condition cannot be ignored).

Also, a checked exception is used when the condition is recoverable. This means that when you use a checked exception, there is a reasonable assumption that the programmer can recover from this exception.

Use runtime exceptions to indicate programming errors. For example, you can use an IllegalArgumentException if a precondition for your method is violated. Considering your example, this exception may make more sense.

If you can use an appropriate standard-exception in place of a checked exception, do so instead of creating a new exception that mimics existing functionality (DRY).

Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
  • public class InvalidTestScoreException extends Exception { public InvalidTestScoreException() { super("Invalid test score"); } public InvalidTestScoreException(String message) { super(message); } public InvalidTestScore(Throwable throwable) { super(throwable); } } – user599272 Feb 07 '11 at 22:17
  • I was a little too quick on my last edit and I wrote `InvalidTestScore` instead of `InvalidTestScoreException`. I've fixed it. – Vivin Paliath Feb 07 '11 at 22:18
  • It still doesn't work when i add your latest edit to my code?. – user599272 Feb 07 '11 at 22:22
  • @user599272 What are you trying to do? – Vivin Paliath Feb 07 '11 at 22:22
  • are you throwing it with `new InvalidTestScoreException()` or are you doing `new InvalidTestScore()`? The latter won't work; Java doesn't know what type it is because you haven't defined it. – Vivin Paliath Feb 07 '11 at 22:23
  • new InvalidTestScore() how do i define it. – user599272 Feb 07 '11 at 22:25
  • use `InvalidTestScoreException` instead of `InvalidTestScore`. – Vivin Paliath Feb 07 '11 at 22:27
  • I did that and i get InvalidTestScoreException cannot be resolved to a type. – user599272 Feb 07 '11 at 22:29
  • I'm not sure what you're doing or trying to do. Not trying to be rude, but I think you may need to brush up on a lot of Java basics (compiling, creating classes, etc.) – Vivin Paliath Feb 07 '11 at 22:31
  • I'm college student trying to learn java for class. I've attempted this but it's not working. – user599272 Feb 07 '11 at 22:33
  • You should look up your class notes and do some research. We can't do all your work for you, or you won't learn. We've told you how to create checked exceptions. The rest is up to you. – Vivin Paliath Feb 07 '11 at 22:35
  • I could really use your help. – user599272 Feb 07 '11 at 22:35
  • @user599272 Google is your friend :) Also, try searching questions on SO. They may give you some more info. On SO we really don't try to help people finish their homework since that defeats the purpose. Good luck. – Vivin Paliath Feb 07 '11 at 22:36
  • If you still have problems, add your current code and all the error messages to your question. (And remove these superfluous empty lines of your example.) – Paŭlo Ebermann Feb 07 '11 at 23:15
2
class MyCustomException extends Exception
{
    public MyCustomException(String message)
    {
        super(message);
    }
}
javanna
  • 59,145
  • 14
  • 144
  • 125
Girish Rao
  • 2,609
  • 1
  • 20
  • 24
1

You simply extend the Exception class. Like this:

class InvalidTestScore extends Exception {
}

Also, here are a few useful constructors that I usually implement.

    public InvalidTestScore(String msg) {
        super(msg);
    }

    public InvalidTestScore(Throwable cause) {
        super(cause);
    }

Here is the official trail on exception handling: The Java Tutorials: Lesson: Exceptions

aioobe
  • 413,195
  • 112
  • 811
  • 826