본문 바로가기

[JAVA] 개발

Java Software Solution Ch11_PP3 ; Exception Class

PP 11.3

Suppose in a particular business all documents are given a twocharacter designation starting with either U, C, or P, standing for unclassified, confidential, or proprietary. Create an exception class called InvalidDocumentCodeException, designed to be thrown when an improper designation for a document is encountered during processing. If a document designation is encountered that doesn’t fit that description, the exception is thrown. Create a driver program to test the exception, allowing it to terminate the program.

 

PP11_3.java

import java.util.Scanner;

public class PP11_3 {
	public static void main(String[] args) {
		System.out.println("Starting with either U, C, or P, standing for unclassified, confidential, or proprietary. : ");
		Scanner scanner = new Scanner(System.in);
		String UCP = scanner.next();
		DocumentCode doc = new DocumentCode(UCP);
		System.out.println(doc);
	}
}

 

DocumentCode.java

public class DocumentCode {
	private String designation = " ";
	public DocumentCode(String ucp) {
		try {
			if(ucp.compareToIgnoreCase("U")!=0 &&
					ucp.compareToIgnoreCase("C")!=0 &&
					ucp.compareToIgnoreCase("P")!=0)
				throw new InvalidDocumentCodeException();
				designation = ucp;
		} catch(InvalidDocumentCodeException e) {
			System.out.println("Invalid Character"+e);
			System.out.println(e.getMessage());
		}
	}
	public String toString() {
		if(designation.compareToIgnoreCase("U")==0 ||
				designation.compareToIgnoreCase("C")==0 ||
				designation.compareToIgnoreCase("P")==0 )
			return designation.toUpperCase();
		else return " ";
	}
}

 

InvalidDocumentCodeException.java

public class InvalidDocumentCodeException extends Exception{
	public InvalidDocumentCodeException() {}
	public String getMessage() { return "starting with either U, C, or P, standing for unclassified, confidential, or proprietary." ; }
}

 

< Console >

Starting with either U, C, or P, standing for unclassified, confidential, or proprietary. : 
u
U