Writing and throwing your own exceptions:

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

public class ExceptionTest {

    public static void main(String [] args) 
	            throws LetterGradeException {
	LetterGrade lg1 = new LetterGrade("B");
	//LetterGrade lg2 = new LetterGrade("F-");
	System.out.println(lg1.lessThan("B"));
	System.out.println(lg1.lessThan("C-"));
	//System.out.println(lg1.lessThan("I"));
	
	LetterGrade lg3 = new LetterGrade(77.8);
	LetterGrade lg4 = new LetterGrade(40.3);
	LetterGrade lg5 = new LetterGrade(102.9);
    }

}

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 LetterGrade(double percent) throws 
                       InvalidPercentGradeValueException{
	    if(percent > 100 || percent < 0){
		    throw new InvalidPercentGradeValueException(percent);
	    }
	    
	    // this should've been a WAY longer if/else sequence,
	    // but we have simplified it:
	    if(percent > 70){
		    lettergrade = "A";
	    } else {
		    lettergrade = "F";
	    }
    }

    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;
    }

    private int getIndex() {
	int inttemp = -1;
	    for (int i = 0; i < possiblevalues.length; ++i) {
		if (lettergrade.equals(possiblevalues[i])) {
		    inttemp = i;
		}
	    }
	return inttemp;
    }
    
    public boolean lessThan(String letter) throws InvalidLetterGradeValueException {
	    LetterGrade temp = new LetterGrade(letter);
	    return this.lessThan(temp);
    }
    
    public boolean lessThan(LetterGrade grade) {
	    boolean flag = false;
	    int thIndex = this.getIndex();
	    int grIndex = grade.getIndex();
	    if (grIndex < thIndex) {
		    flag = true;
	    }
	    return flag;
    }
}

class InvalidLetterGradeValueException extends LetterGradeException {

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

class LetterGradeException extends Exception{
	
	public LetterGradeException(String message){
		super(message);
	}
}

class InvalidPercentGradeValueException extends LetterGradeException{
	
	public InvalidPercentGradeValueException(double percent){
		super("Value " + percent + " is out of range");
	}
}



This is an example from CSci 2101 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.