Writing and throwing your own exceptions:

import java.awt.*;
import java.util.*;

public class ExceptionTest {

    public static void main(String [] args) 
	            throws InvalidLetterGradeValueException {
	LetterGrade lg1 = new LetterGrade("B");
	LetterGrade lg2 = new LetterGrade("F-");
    }

}

class LetterGrade {
    private String lettergrade;
    private static String [] possiblevalues = {"A","A-","B+","B","B-",
					    "C+","C","C-","D+","D",
					    "D-","F"};

    public LetterGrade(String letter) throws InvalidLetterGradeValueException {
	if (!isValid(letter)) {
	    throw new InvalidLetterGradeValueException(letter);
	}
	lettergrade = letter;
    }

    public static boolean isValid(String letter) {
	for (int i = 0; i < possiblevalues.length; ++i) {
	    if (letter.equals(possiblevalues[i])) {
		return true;
	    }
	}
	return false;
    }

    public String getValue() {
	return lettergrade;
    }

    
}

class InvalidLetterGradeValueException extends Exception {

    public InvalidLetterGradeValueException(String letter){
	super("Value " + letter + " is out of range");
    }
}

This is an example from CSci 1211 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.